I have this Jqplot pie chart with some cut-out slices:
var data = [['SliceOfSlices', 60],['a', 10],['b', 5],['c', 25],['d', 10],];
plot = $.jqplot('pie-graph', [data], {
title: 'Slices',
seriesDefaults: {
renderer: $.jqplot.PieRenderer,
rendererOptions: {
sliceMargin: 8,
}
}
});
JSFiddle here.
What I'd like to do is to let one of the slices contain slices of its own, without cutting them up. Like so:
I've looked around and I suspect this might be stretching the capabilities of the jqplot library a bit far... Just thought I'd ask.
Related
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);
}
}
In jqplot, why is the auto scaling on bar charts so very different from on line charts?
Using the exact same data, I get these two plots:
The options I use for the two plots are:
var bar_options = {
axesDefaults: { labelRenderer: $.jqplot.CanvasAxisLabelRenderer },
seriesDefaults: { renderer: $.jqplot.BarRenderer, rendererOptions: { highlightMouseOver:false, barMargin:5, shadowOffset:1 } },
axes: { xaxis: { renderer: $.jqplot.CategoryAxisRenderer }, yaxis: { tickOptions:{show:false} } },
};
and
var line_options = {
axesDefaults: { labelRenderer: $.jqplot.CanvasAxisLabelRenderer },
seriesDefaults: { rendererOptions: { smooth: true } },
axes: { xaxis: { min:1, max:30, tickInterval:1, pad:0 }, yaxis: { tickOptions:{show:false} } },
};
The line plot looks really good, but the bar chart is next to useless with the scaling shown.
Why is the default scaling so different between the two plots, and how can I get the scaling on the bar plot to be the same as the line graph?
EDIT:
I have created a simpler example, with data as follows:
[38.23, 39.33, 41.67, 40.21, 45.01, 44.47, 37.04]
And the resulting graph shown is this:
Adding a y-axis scale, shows that the data is starting from 0.
I changed my plot code to this...
var home_bar_options = {
axesDefaults: { labelRenderer: $.jqplot.CanvasAxisLabelRenderer },
seriesDefaults: { renderer: $.jqplot.BarRenderer, rendererOptions: { highlightMouseOver:false, barMargin:5, shadowOffset:1 } },
axes: { xaxis: { renderer: $.jqplot.CategoryAxisRenderer }, yaxis: { min:30, max:50 } }
};
But the plot doesn't change, and completely ignores the 'min' and 'max' values that I have entered for the y-axis scale.
Why is this?
I have not found any 'proper' way to move the axis on the bar chart, but I have managed to find a workaround.
My page is in PHP, and the data is coming from a mysql database.
So, after I have the data, and before I draw the bar chart plot, I get the minimum data value, and subtract that value from all my data!
So if my data is
35, 38, 36, 42, 40
I subtract 35 from all data, giving a new data set of
0, 3, 1, 7, 5
The bar chart will then plot this in a much better looking way!
Because I don't need to see actual data numbers, just the trend, this works ok for me - but wouldn't work if you needed a y-axis with a scale.
If anyone has a 'proper' way to properly adjust the bar plot y-axis away from zero, then I would be very happy to hear it!
But, for now, my workaround will suffice!
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.
I'm new to jqplot, when I want to draw a bar chart, x axis is date, interval is 1 day. This is part of my code:
axesDefaults:{
tickRenderer: $.jqplot.CanvasAxisTickRenderer,
tickOptions:{
fontSize:'10pt',
},
},
axes:{
xaxis:{
renderer:$x_renderer,
tickOptions:{
formatString:'%Y-%#m-%#d',
},
rendererOptions:{
tickOptions:{
angle:-90,
}
},
label:'$label',
tickInterval:'86400000',
},
yaxis:{
tickOptions:{
formatString:'%.2f',
},
autoscale:true
},
},
highlighter:{
show:true,
},
But I find the width of each bar is too large to cover each other. How to fix it?
Thanks!
The AnthonyLeGovic answer is indeed correct, but if you need to change the column width according to the number of data points you can do the following:
// Get the size of the container of the plot
var width = jQuery(containerName).width();
// Divide by the number of data points.
width = width / number_of_data_points;
// Reduce the width to a % of the total for each data point.
width = (width * 20) / 100;
// Set the value
$.jqplot(containerName, [data],
{
// whatever
// ...
seriesDefault:
{
renderer: $.jqplot.BarRenderer,
rendererOptions: { barWidth: width }
}
// whatever
// ...
}
Note that I'm not taking into account the width of the legend. The legend width can only be obtained after plotting, so if you want to reduce the column width considering even the width of the legend you must do it after plotting, and then replot.
I've prepared a fiddle that shows an example.
Hope it helps.
You can specify it in your series options :
seriesDefault:{
renderer: $.jqplot.BarRenderer,
rendererOptions: {
barWidth: 5
}
}
Don't forget to include barRenderer plugins.
For more documentations about bar chart on jqplot please take a look at : Jqplot documentation
I added below code and I got the result.
The reason behind my width was coming too large because of bar-width were not set in series Default block.
seriesDefault:{
renderer: $.jqplot.BarRenderer,
rendererOptions: {
barWidth: 5
}
}
Thanks to :AnthonyLeGovic
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?