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
You need to edit the generateLabels
property in your options :
options: { legend: { labels: { generateLabels: function(chart) { // Here } } } }
Here are a small jsFiddle, where you can see how it works (edited lines - from 38 - are commented), and its result :
Maybe this is a hacky solution, but for me seems simpler.
filter
parameterChartJS legend options have a filter
parameter. This is a function that is called for each legend item, and that returns true/false whether you want to show this item in the legend or not.
filter
has 2 arguments:
legendItem
: The legend item to show/omit. Its properties are described here data
: The data object passed to the chart.Since JS passes objects by reference, and filter
is called for each legend item, then you can mutate the legendItem
object to show the text that you want.
legend : { labels: { filter: (legendItem, data) => { // First, retrieve the data corresponding to that label const label = legendItem.text const labelIndex = _.findIndex(data.labels, (labelName) => labelName === label) // I'm using lodash here const qtd = data.datasets[0].data[labelIndex] // Second, mutate the legendItem to include the new text legendItem.text = `${legendItem.text} : ${qtd}` // Third, the filter method expects a bool, so return true to show the modified legendItem in the legend return true } } }
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