Correctly Displaying Percentage Values in Chart.js Pie Charts Using the datalabels Plugin

Dec 03, 2025 · Programming · 9 views · 7.8

Keywords: ChartJS | Pie Chart | Percentage | datalabels | JavaScript

Abstract: This article explains how to accurately calculate and display percentage values in Chart.js pie charts using the chartjs-plugin-datalabels plugin. It covers a common error where all slices show 100%, and provides a corrected solution with code examples and detailed explanations to ensure accurate data visualization.

In data visualization, pie charts are commonly used to represent percentage distributions, and Chart.js is a popular JavaScript charting library. With the chartjs-plugin-datalabels plugin, developers can easily add data labels. However, when displaying percentage values, a common error occurs where all pie slices show incorrect percentages, such as 100% each.

Error Analysis

In the user's initial code, the formatter function incorrectly calculated the data sum. The original code only considered the current dataset or index, rather than summing all data points. Specifically, during iteration, the sum variable was reassigned without accumulating all values. This led to each percentage being calculated as (value / value) * 100, causing all slices to display 100%. For example, the logic ignored the summation of the entire data array.

Solution

Based on the accepted answer, the correct approach is to compute the total sum of all data points in the dataset and then calculate the percentage for each value. This requires accessing the chart object's data property and iterating through the array for accumulation. The corrected code uses ctx.chart.data.datasets[0].data to retrieve the data array, ensuring accurate sum calculation. The percentage formula is: percentage = (value / sum) * 100, with toFixed(2) used to retain two decimal places for better precision.

Code Implementation

Below is a corrected full code example demonstrating how to configure a Chart.js pie chart to display percentage values.

// Define pie chart data var data = [{ data: [50, 55, 60, 33], labels: ["India", "China", "US", "Canada"], backgroundColor: ["#4b77a9", "#5f255f", "#d21243", "#B27200"], borderColor: "#fff" }]; // Configuration options, including the datalabels plugin var options = { plugins: { datalabels: { formatter: (value, ctx) => { let sum = 0; let dataArr = ctx.chart.data.datasets[0].data; dataArr.forEach(data => { // Use forEach to iterate over all data points sum += data; }); let percentage = (value * 100 / sum).toFixed(2) + "%"; // Calculate percentage and format to two decimals return percentage; }, color: '#fff' // Set label color to white for better readability } } }; // Initialize the chart var ctx = document.getElementById("pie-chart").getContext('2d'); var myChart = new Chart(ctx, { type: 'pie', data: { datasets: data }, options: options });

In this code, the formatter function first initializes sum to 0, then iterates over the dataArr array to accumulate all data values, ensuring the total sum is correct. Next, it calculates the percentage using (value * 100 / sum) and controls decimal places with toFixed(2). Finally, it returns the formatted string as the label content. This method avoids the logical error in the original code, ensuring each pie slice displays the correct percentage.

Conclusion

When displaying percentage values in Chart.js pie charts, the key step is to accurately compute the total data sum. By using the chartjs-plugin-datalabels plugin and a corrected formatter function, developers can enhance the accuracy of data visualization. Common errors include miscalculating the sum or neglecting array iteration, so it is advisable to carefully review code logic and use debugging tools to validate calculations. Additionally, consider adjusting percentage formatting or color settings for better readability in various application scenarios.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.