Pie Chart Legend - Chart.js

I need help to put a pie chart number in a legend

Chart image

If I find a chart with a mouse, I can see the number relative to each element

I want to display it in a legend either

important code:

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

+14
pie-chart legend-properties
Sep 12 '16 at 16:12
source share
2 answers

You need to edit the generateLabels property in your settings:

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




Since it is completely useless to create your own large template. I suggest using the same function as in the source code , and then edit what you need.

Here is a small jsFiddle where you can see how it works (edited lines - out of 38 - commented out) and its result:

enter image description here

+27
Sep 13 '16 at 7:55
source share

I wanted to allow the user to select from 100+ datasets, but instead of adding / removing them from my chart, I decided to set showLine: false for any dataset I want to hide. Unfortunately, the default legend will show all 100+. Therefore, in my solution, I generate the legend manually by filtering out any dataset that showLine: false has showLine: false .

Your settings will have this:

 legend: { labels: { generateLabels: (a) => { return a.data.labels } } 

And you will create your own labels using a helper function:

 function updateAllLabels() { const myNewLabels = []; myChart.data.datasets.forEach((element) => { if (element.showLine) { myNewLabels.push(generateLabel(element)); } }); myChart.data.labels = myNewLabels; } 

And you will generate a label with another function:

 function generateLabel(data) { return { fillStyle: data.borderColor, lineWidth: 1, strokeStyle: data.borderColor, text: data.countyName, // I attach countryName to my datasets for convenience } } 

Now just remember to call the function when updating the chart:

 updateAllLabels(); myChart.update(); 

Have a nice schedule!

0
May 23 '19 at 5:54
source share



All Articles