1👍
✅
You can add the percentage with the formatter function like so:
plugins: {
datalabels: {
backgroundColor: function(context) {
return context.dataset.backgroundColor;
},
formatter: (val, context) => `${val}%`,
borderRadius: 25,
borderWidth: 3,
color: "black",
font: {
weight: "bold"
},
padding: 6
},
tooltip: {
callbacks: {
label: (ttItem) => `${ttItem.label}: ${ttItem.parsed}%`
}
}
}
If instead of only a percentage sign you want the percentages itself to be displayed you will need to calculate them like so:
plugins: {
datalabels: {
backgroundColor: function(context) {
return context.dataset.backgroundColor;
},
formatter: (val, context) =>
`${
(Number(val) * 100) /
context.chart.data.datasets[context.datasetIndex].data.reduce(
(a, b) => Number(a) + Number(b),
0
)
}%`,
//formatter: (val, context) => `${val}%`,
borderRadius: 25,
borderWidth: 3,
color: "black",
font: {
weight: "bold"
},
padding: 6
},
tooltip: {
callbacks: {
label: (ttItem) =>
`${ttItem.label}: ${
(ttItem.parsed * 100) /
ttItem.dataset.data.reduce(
(a, b) => Number(a) + Number(b),
0
)
}%`
//label: (ttItem) => `${ttItem.label}: ${ttItem.parsed}%`
}
}
}
https://codesandbox.io/s/bar-graph-forked-43wzq?file=/src/App.js:3215-3797
Source:stackexchange.com