Is it possible to only hide certain dataset legends in chartjs? I know it is possible to hide all with
options: { legend: { display: false
To remove legend on charts with Chart. js v2 and JavaScript, we can set the options. legend to false . const chart1 = new Chart(canvas, { type: "pie", data: data, options: { legend: { display: false, }, tooltips: { enabled: false, }, }, });
For this, Just tap on the main menu in the upper left corner and from there tap on “Settings” at the bottom. In Settings, tap on “Display settings” and from there uncheck the “Show hidden files” option.
According to the official documentation (https://www.chartjs.org/docs/latest/configuration/legend.html), to hide the legend, the display property of the options. display object must be set to false .
Short answer: Yes it is possible. Unfortunately it's not quite as simple as the developers could make it.
If you know what the text
value of the item being displayed in the legend is, then you can filter that out. After reading through the Chart.js docs I found the section Legend Label Configuration that details a filter
function that can be used to "filter out the legend items", although this function must be set on the parent chart options object, not as an option on the dataset itself:
const chart = new Chart(ctx, { type: 'bar', data: data, options: { legend: { labels: { filter: function(item, chart) { // Logic to remove a particular legend item goes here return !item.text.includes('label to remove'); } } } } });
Now it appears each time the data changes and the chart is updated via chart.update()
this filter function is called.
For convenience I have set this up in a jsfiddle for you to play with.
Note: This solution was designed around the API for version 2.7.1 of ChartJS. Future versions may improve the control over dataset legend labels.
In my case, changing the label to "hidden" caused that to show in the tooltip, instead of the text I wanted.
So here's a way you can target each dataset's legend by it's index number without changing the label!
const chart = new Chart(ctx, { type: 'bar', data: data, options: { legend: { labels: { filter: function(item, chart) { return item.datasetIndex !== INDEX_OF_DATASET && item.datasetIndex !== INDEX_OF_ANOTHER_DATASET; } } } } });
In my case, I'm using wpDataTables to create a chart in WordPress, so the code looks like this:
wpDataChartsCallbacks[INDEX_OF_CHART_HERE] = function (obj) { obj.options.options.legend.labels.filter = function(item, chart) { return item.datasetIndex !== INDEX_OF_DATASET && item.datasetIndex !== INDEX_OF_ANOTHER_DATASET; } }
It's working great for me!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With