chart.js show percentage in pie chart
Updated: 28th March 2023
Tags: javascript chart.js
If you want to customize chat.js label and title to behave like google pie chart, so we have label<br>50 (50.0%)
you’ll need to dirty your hands and waste an hour.
Fortunately, I’ve done this and you can copy and paste
Chart.defaults.plugins.tooltip.callbacks.label = function (context) {
const total = context.dataset.data.reduce((x, y) => x + y, 0);
const currentValue = context.parsed;
const percentage = ((currentValue / total) * 100).toFixed(2);
return `${currentValue} (${percentage}%)`;
};
Chart.defaults.plugins.tooltip.callbacks.title = function (context) {
return context.label;
};
This snippet will do it. Demo Here full code example:
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.2.1/chart.umd.min.js" integrity="sha512-GCiwmzA0bNGVsp1otzTJ4LWQT2jjGJENLGyLlerlzckNI30moi2EQT0AfRI7fLYYYDKR+7hnuh35r3y1uJzugw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div style="max-width: 500px;"><canvas id="fruits"></canvas></div>
<script>
Chart.defaults.plugins.tooltip.callbacks.label = function (context) {
const total = context.dataset.data.reduce((x, y) => x + y, 0);
const currentValue = context.parsed;
const percentage = ((currentValue / total) * 100).toFixed(2);
return `${currentValue} (${percentage}%)`;
};
Chart.defaults.plugins.tooltip.callbacks.title = function (context) {
return context.label;
};
/// Demo chart
const CHART_COLORS = {
red: "rgb(255, 99, 132)",
orange: "rgb(255, 159, 64)",
yellow: "rgb(255, 205, 86)",
green: "rgb(75, 192, 192)",
blue: "rgb(54, 162, 235)",
purple: "rgb(153, 102, 255)",
grey: "rgb(201, 203, 207)"
};
new Chart(document.getElementById("fruits"), {
type: "pie",
data: {
labels: ["apple", "lemon", "tomato"],
datasets: [
{
data: [50, 20, 30],
backgroundColor: Object.values(CHART_COLORS),
hoverOffset: 4
}
]
},
options: {
responsive: true,
plugins: {
legend: {
position: "top"
},
title: {
display: true,
text: "I eat following fruits last week:"
}
}
}
});
</script>