Pie Chart Legend - Chart.js

dpanegassi picture dpanegassi · Sep 12, 2016 · Viewed 35.6k times · Source

I need help to put the number of the pie chart in the legend

Chart Image

If i hover the chart with mouse i can see the number relative to each item

i want to display it in the legend either

the important code so far:

var tempData = {
    labels: Status,
    datasets: [
        {
            label: "Status",
            data: Qtd,
            backgroundColor: randColor
        },

    ]
};

var ctx = $("#pieStatus").get(0).getContext("2d");
var chartInstance = new Chart(ctx, {
    type: 'pie',
    data: tempData,
    options: {
         title: {
            display: true,
            fontsize: 14,
            text: 'Total de Pedidos por Situação'
        },
        legend: {
            display: true,
            position: 'bottom',

        },
        responsive: false
    }

});

"Qtd","randColor" are "var" already with values

Answer

tektiv picture tektiv · Sep 13, 2016

You need to edit the generateLabels property in your options :

options: {
    legend: {
        labels: {
            generateLabels: function(chart) {
                 // Here
            }
        }
    }
}


Since it is quite a mess to create on your own a great template. I suggest using the same function as in the source code and then edit what is needed.

Here are a small jsFiddle, where you can see how it works (edited lines - from 38 - are commented), and its result :

enter image description here