Chart.js: How to get bar chart labels clickable? - label

I use chart.js 2.8.0 to create mainly pie and bar charts. The clickable legend on pie charts is really useful, filtering out unwanted data from the result.
When creating a chart there are two kinds of labels:
* An array of labels on chart level, label 1 corresponding to item 1 in each dataset.
* Dataset labels, one for each dataset.
A pie chart as standard get the chart label array turned into a legend with clickable labels, click on a label and that item is filtered out from the chart.
A bar chart, on the other hand, gets the labels shown below the bar but not clickable. Instead the legend here is made out of the dataset label. If you have more than one dataset, a whole dataset is filtered out if you click on that label.
Since I sometimes have several datasets I can not use the "trick" that consists of putting data item into a separate dataset (that was otherwise the closest to what I wanted that I found in my search, the "extra" clickable legend that would create would work as well). The situation is also that the end user should get a drop-down (or similar) so he, from the same data, can select chart type. So the soultion need to work both for pie and bar charts. the same data and (standard) code creates the two shown charts (except for the colors).
The question is now, as stated in the title: Is it possible to get clickable labels for a bar chart with the same filtering functionality as when the chart is of pie type?
I understand that it isn't doable by just setting some options, it would probably have to be done by creating a plugin, but is it at all doable? if so, any pointers for help?
If not clickable labels, maybe make the bars themselves clickable (with the same result)...?
With a slight change to the fiddle given by https://stackoverflow.com/users/3963330/tob%c3%adas in his answer here: Click events on Pie Charts in Chart.js I get a fiddle that also can handle multiple datasets, and on my second try I managed to hide a segment when I clicked on it. And then I relized that if it wasn't a pie chart there would be no clickable legend to use for unhiding that element - so that's not a solution for my bar charts.
Tried combining a couple of SO questions/answers (generating labels by #GRUNT : Bar labels in Legend) but can't get legend labels for bar charts to filter out segments instead of datasets.
Fiddle: https://jsfiddle.net/tommypeters/24ra6egy/9/
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="canvas"></canvas>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
var myNewChart = new Chart(ctx, {
type: 'bar',
data: {
datasets: [{
data: [300, 50, 100],
backgroundColor: [
"#F7464A",
"#46BFBD",
"#FDB45C"
]
},
{
data: [400, 60, 101],
backgroundColor: [
"#F7464A",
"#46BFBD",
"#FDB45C"
]
}
],
labels: [
"Red",
"Green",
"Yellow"
]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
legend: {
labels: {
generateLabels: function(chart) {
var labels = chart.data.labels;
var dataset = chart.data.datasets[0];
var legend = labels.map(function(label, index) {
return {
datasetIndex: 0,
fillStyle: dataset.backgroundColor && dataset.backgroundColor[index],
strokeStyle: dataset.borderColor && dataset.borderColor[index],
lineWidth: dataset.borderWidth,
text: label
}
});
return legend;
}
}
}
}
});
canvas.onclick = function(evt) {
var activePoints = myNewChart.getElementsAtEvent(evt);
if (activePoints[0]) {
var chartData = activePoints[0]['_chart'].config.data;
var idx = activePoints[0]['_index'];
var dIndex = myNewChart.getDatasetAtEvent(evt)[0]._datasetIndex;
var label = chartData.labels[idx];
var value = chartData.datasets[dIndex].data[idx];
// Doesn't hide a slice but a whole dataset...
// var meta = myNewChart.getDatasetMeta(dIndex);
// meta.hidden = meta.hidden === null ? !myNewChart.data.datasets[dIndex].hidden : null;
// myNewChart.update();
var i, ilen, meta;
for (i = 0, ilen = (myNewChart.data.datasets || []).length; i < ilen; ++i) {
meta = myNewChart.getDatasetMeta(i);
if (meta.data[idx]) {
meta.data[idx].hidden = !meta.data[idx].hidden;
}
}
myNewChart.update();
var url = "http://example.com/?label=" + label + "&value=" + value;
console.log(url);
alert(url);
}
}

Related

how can i change the colors of title boxes in amcharts

I have changed my chart colors but the title boxes are not changed. How can I change them
POLAR SCATTER CHARTS
Legend markers ignore bulletColor by default. You have two options to change the marker color:
1) Set lineColor to change your legend marker and bullet colors instead of using bulletColor.
var chart = AmCharts.makeChart("chartdiv", {
// ..
"graphs": [{
"lineColor": "#000088",
// ... omitted ..
},
// ... etc
],
// ...
});
Demo
2) If you rather use bulletColor, you can set useGraphSettings to true in your legend, which makes your legend use your bulletColor but changes your markers to bullets instead of boxes.
var chart = AmCharts.makeChart("chartdiv", {
// ...
"legend": {
"useGraphSettings": true,
// ...
},
// rest stays the same
});
Demo

How to handle No Data in pie chart?

I am currently working with pie charts in amCharts plugin. Sometimes I had to face no data in pie chart. In this scenario, amCharts loads no graph.
How can I handle no data in pie chart? Is there any method to display inactive pie chart (disabled pie chart or something)?
You can use AmCharts.addInitHandler function to set custom function to call before chart is drawn. You can use it to check if dataProvider is empty and make all kinds of modifications to the chart.
I.e.:
/**
* amCharts Plugin: handle empty pie chart
*/
AmCharts.addInitHandler(function(chart) {
// check if data is mepty
if (chart.dataProvider === undefined || chart.dataProvider.length === 0) {
// add some bogus data
var dp = {};
dp[chart.titleField] = "";
dp[chart.valueField] = 1;
chart.dataProvider.push(dp)
var dp = {};
dp[chart.titleField] = "";
dp[chart.valueField] = 1;
chart.dataProvider.push(dp)
var dp = {};
dp[chart.titleField] = "";
dp[chart.valueField] = 1;
chart.dataProvider.push(dp)
// disable slice labels and balloons
chart.labelsEnabled = false;
chart.balloonText = "";
// add label to let users know the chart is empty
chart.addLabel("50%", "50%", "The chart contains no data", "middle", 15);
// dim the whole chart
chart.alpha = 0.3;
}
}, ["pie"]);
var chart = AmCharts.makeChart("chartdiv", {
"type": "pie",
"theme": "light",
"dataProvider": [],
"valueField": "value",
"titleField": "title"
});
<script src="http://www.amcharts.com/lib/3/amcharts.js"></script>
<script src="http://www.amcharts.com/lib/3/pie.js"></script>
<script src="http://www.amcharts.com/lib/3/themes/light.js"></script>
<div id="chartdiv" style="width: 100%; height: 400px;"></div>

jqplot pie chart percentage adding

Consider this code snippet:
function drawChart() {
var slice_1 = ['A', 15];
var slice_2 = ['B', 40];
var slice_3 = ['C', 50];
var slice_4 = ['D', 40];
var series = [slice_1, slice_2, slice_3,slice_4];
var data = [series];
var options = {
seriesColors: ["#00aeef", "#FFBF00", "#0CDA08", "#FF1926"],
seriesDefaults: {
renderer: jQuery.jqplot.PieRenderer
},
legend: { show:true, location: 'e' }
};
$.jqplot('chartDivId', data, options);
}
In the above, how do i get percentage inside the pie chart? I tried many things but can;t make it work.
I added this:
rendererOptions: {
// Put data labels on the pie slices.
// By default, labels show the percentage of the slice.
showDataLabels: true,
dataLabels: 'value',
dataLabelFormatString:'%.4f'
}
But percentage didn't appear inside the pie chart.
I used the above snippet (the one you posted) and I was able to display labels in 'percentages'
You just need to use showDataLabels: true inside rendererOptions
By default, showDataLabels displays the labels in percentages.
No need for the code below. Remove these two lines
dataLabels: 'value',
dataLabelFormatString:'%.4f'
Here's a working JSFiddle for your code : Pie Chart - Show labels in percentages
Also make sure that you add rendererOptions inside seriesDefaults
You can also check the example over here: jqPlot - Pie Chart
Hope it helps.

jqplot help for barclustered type chart

hFollowing is the code for barclustered jqplot. can anyone please guide me gow to create a highlighted array in following code dynamically
$(document).ready(function(){
// For horizontal bar charts, x an y values must will be "flipped"
// from their vertical bar counterpart.
var plot2 = $.jqplot('chart2', [
[[2,1], [4,2], [6,3], [3,4]],
[[5,1], [1,2], [3,3], [4,4]],
[[4,1], [7,2], [1,3], [2,4]]], {
seriesDefaults: {
renderer:$.jqplot.BarRenderer,
// Show point labels to the right ('e'ast) of each bar.
// edgeTolerance of -15 allows labels flow outside the grid
// up to 15 pixels. If they flow out more than that, they
// will be hidden.
pointLabels: { show: true, location: 'e', edgeTolerance: -15 },
// Rotate the bar shadow as if bar is lit from top right.
shadowAngle: 135,
// Here's where we tell the chart it is oriented horizontally.
rendererOptions: {
barDirection: 'horizontal'
}
},
axes: {
yaxis: {
renderer: $.jqplot.CategoryAxisRenderer
}
}
});
});
You have a problem with your Javascript syntax and algorithm. The loop should looks like :
VData="9,453,470,232|488,378,375,142|365,275,255,434|217,317,479,89";
var a = new Array();
var split_fst = VData.split("|")
for(m=0;m<split_fst.length;m++) {
var split_snd = split_fst[m].split(",");
a[m] = new Array();
for(j=0;j<split_snd.length;j++){
a[m][j]=split_snd[j];
}
}
Your a variable now looks like : `[["9","453","470","232"],["488","378","375","142"],["365","275","255","434"],["217","317","479","89"]]

Fill all slices of jqplot pie chart in mvc3

I am creating a jQuery mobile app using the mvc3. In this I have created the jqPlot pie chart.
It does not show colors for all slices of the pie chart,
i.e it sometimes show color for one slice even when there are four slices in the chart, and for the other three slices it shows white background instead of its defined slice background color.
I want it to show every time a full chart with solid color fill.
The image of jqPlot pie-chart:
http://i.stack.imgur.com/qH4o9.png
I am using this code:
jQuery(document).ready(function ($) {
var data = [
['Correct Answers', #Correct_Answer], ['Incorrect Answers', #Incorrect_Answer], ['Skipped Answers', #Skipped_Answer],
['Unseen Answers', #Unseen_Answer]
];
var plot1 = $.jqplot('score_chart', [data],
{
seriesColors: ["#83abc0", "#64d6f4", "#3399ff", "#03597a"],
highlightColors: ["#ADC7D5", "#99E3F6", "#78BAFE", "#568FA6"],
seriesDefaults: {
// Make this a pie chart.
fill: true,
renderer: $.jqplot.PieRenderer,
rendererOptions: {
// Put data labels on the pie slices.
// By default, labels show the percentage of the slice.
padding: 5,
fill: true,
fillAndStroke: true,
showDataLabels: true
}
},
legend: { show: true, location: legendlocation },
});
});
Can anyone help me with this issue?
Your problem is not in this code. I did a sample from the code you have provided and it works fine. See here.
Are you sure you have all JavaScript and CSS files correctly imported?

Resources