Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chart.js HTML custom legend issues with doughnut chart

I'm working with chart.js and I followed this to create a custom HTML legend. The thing is, the hide/show functionality is not working. The first legend click hides the whole chart, while the others produce the error:

Uncaught TypeError: Cannot read property '_meta' of undefined
    at t.getDatasetMeta (Chart.min.self-b26766dbef822c075056eb7012dc36ae75970dc990497732f927d46ef6070858.js:11)
    at HTMLLIElement.legendClickCallback (plot.self-416475a747a420b91c7fab454c07846f1043f55cc28f6d810fafeab61c56cf01.js:317)

so it traces back to t.getDatasetMeta. I gotta say it's working great with line/bar charts, so its only my doughnut chart which breaks. Let me know if you need more info. Oh and thanks :P

EDIT: fiddle

like image 724
Johnny Avatar asked Jan 08 '18 16:01

Johnny


People also ask

How do you add a legend to a donut chart?

Click the chart, and then click the Chart Design tab. Click Add Chart Element > Legend. To change the position of the legend, choose Right, Top, Left, or Bottom. To change the format of the legend, click More Legend Options, and then make the format changes that you want.

How do I get rid of legend in Doughnut chart?

Tip: To quickly remove a legend or a legend entry from a chart, you can select it, and then press DELETE. You can also right-click the legend or a legend entry, and then click Delete.


1 Answers

The problem is that you have only one dataset and your code use the index of legend item clicked to hide datasets[index].

On the contrary you need to hide single item data as below:

var meta = chart.getDatasetMeta(0);
var item = meta.data[index];

Check the fiddle updated: https://jsfiddle.net/beaver71/aa2n39s2/

like image 171
beaver Avatar answered Sep 20 '22 20:09

beaver