Current it is easy to remove the legend from charts via the global or chart level config options. However, it would be very useful for me to be able to remove the legend on a per-dataset level.
Currently:
options: {
legend: {
display: false
}
}
Requested API:
var lineChartData = {
labels: [],
datasets: [{
label: '',
data: [],
}, {
data: []
legend: false,
}]
}
hi, i had the same problem and developed the following patch to support a new dataset-attribute hiddenLegend: true|false
--- node_modules/chart.js/dist/Chart.js 2016-08-27 14:39:31.000000000 +0200
+++ Chart.js
@@ -6293,6 +6293,7 @@
lineWidth: dataset.borderWidth,
strokeStyle: dataset.borderColor,
pointStyle: dataset.pointStyle,
+ hiddenLegend: dataset.hiddenLegend,
// Below is extra data used for toggling the datasets
datasetIndex: i
@@ -6551,7 +6552,8 @@
// current position
var drawLegendBox = function(x, y, legendItem) {
- if (isNaN(boxWidth) || boxWidth <= 0) {
+
+ if (isNaN(boxWidth) || boxWidth <= 0 || legendItem.hiddenLegend) {
return;
}
@@ -6590,6 +6592,9 @@
ctx.restore();
};
var fillText = function(x, y, legendItem, textWidth) {
+
+ if(legendItem.hiddenLegend) { return; }
+
ctx.fillText(legendItem.text, boxWidth + (fontSize / 2) + x, y);
if (legendItem.hidden) {
Hi I'm using 2.0.2 and I need this patch but it doesn't work:
$ patch Chart.js chartsjs.patch
patching file Chart.js
Hunk # 1 FAILED at 6293.
Hunk # 2 FAILED at 6551.
Hunk # 3 FAILED at 6590.
3 out of 3 hunks FAILED -- saving rejects to file Chart.js.rej
What version was the patch for @mcpohl ?
the version was 2.2.2
I'm trying to use this feature on 2.7.0 but the legend item is still being displayed for the dataaset. Am I doing something wrong?
datasets: [
{
label: 'Primary Line',
data: [12, 19, 3, 2, 9],
borderColor: 'rgb(0, 12, 192)',
borderWidth: 2,
hiddenLegend: true,
}
]
v2.7.0
Under options, add the following:
options: {
legend: {
labels: {
filter: function(legendItem, chartData) {
// return true or false based on legendItem's datasetIndex (legendItem.datasetIndex)
}
}
}
}
Angular\Typescript:
options: {
legend: {
labels: {
filter: (legendItem, chartData) => {
// return true or false based on legendItem's datasetIndex (legendItem.datasetIndex)
}
}
}
}
I had to use legendItem.index instead of legendItem.datasetIndex with version 2.7.2.
Here's the code I used to hide items in the legend that had "empty" data:
options: {
labels: {
filter: function (legendItem, chartData) {
return chartData.datasets[0].data[legendItem.index] > 0;
},
},
},
i try this, but it does not work, weird
I tried this, but it is not working. Can anyone tell me how can I achieve this?
legend: {
display: true,
labels: {
filter: function (legendItem, chartData) {
return (chartData.datasets[legendItem.datasetIndex].label)
},
}
},
Remove label from dataset you want to hide and this should do the magic.
Most helpful comment
v2.7.0
Under options, add the following:
Angular\Typescript: