score:9

Accepted answer

chart.js v2 has a completely different api than earlier versions. you should read the new documentation carefully before upgrading (and then having to wonder what wen't wrong).

the fundamental changes (related to your question) are:

  • legendtemplate and segments are not available anymore. you should instead use legendcallback (in options) to override the default legend implementation. here's what the documentation says about this callback:

function to generate a legend. receives the chart object to generate a legend from. default implementation returns an html string.

  • the data you used from segments are available in the chart parameter (i.e. your actual chart object) of your legendcallback function here: chart.data.datasets[0].data.
  • now that we know where to get our required data from, we can loop through chart.data.datasets[0].data to collect the values and append them to the legend html string.
  • then we can simply call mypiechart.generatelegend(), which will invoke our legendcallback.

complete example:

var mypiechart = new chart(ctx, {
    type: 'pie',
    data: d,
    options: {
        responsive: true,
        maintainaspectratio: false,
        tooltips: {
            callbacks: {
                label: function (tooltipitem, data) {
                    return data.labels[tooltipitem.index] + ' (' + data.datasets[tooltipitem.datasetindex].data[tooltipitem.index] + '%)';
                }
            }
        },
        legendcallback: function (chart) {
            var text = [];
            text.push('<ul class="' + chart.id + '-legend">');

            var data = chart.data;
            var datasets = data.datasets;
            var labels = data.labels;

            if (datasets.length) {
                for (var i = 0; i < datasets[0].data.length; ++i) {
                    text.push('<li><span style="background-color:' + datasets[0].backgroundcolor[i] + '"></span>');
                    if (labels[i]) {
                        text.push(labels[i] + ' (' + datasets[0].data[i] + '%)');
                    }
                    text.push('</li>');
                }
            }
            text.push('</ul>');
            return text.join('');
        },
        legend: {
            // since you're providing your own legend
            display: false,
        },                
    }
});

var legend = mypiechart.generatelegend();
document.getelementbyid("legend").innerhtml = legend;

for purposes of completeness, i've also added the same text (percentage%) template on the tooltips labels (which similarly to legends, provide their own callbacks for overriding default implementations).

i would also suggest browsing through the actual chart.js source code, in particular having a look at legendcallback, generatelegend(), etc, to gain a better understanding of how things work under the hood.


Related Query

More Query from same tag