ArticleZip > Chartjs Datalabels Show Percentage Value In Pie Piece

Chartjs Datalabels Show Percentage Value In Pie Piece

When using Chart.js to create a pie chart, adding data labels to display the percentage values within each chart slice can provide valuable insights to your audience. In this tutorial, we will guide you through the process of showing percentage values in pie chart pieces using Chart.js DataLabels plugin.

To begin, make sure you have Chart.js installed and set up in your project. Then, you will need to include the Chart.js DataLabels plugin in your project. You can easily do this by adding the plugin script after the Chart.js script in your HTML file.

Next, let's dive into the code. When configuring your pie chart using Chart.js, you can add the `plugins` property to the configuration object and set it to an array containing an object with the `datalabels` key. This object allows you to customize how the data labels are displayed in the chart.

Here's an example code snippet demonstrating how to show percentage values in pie chart pieces using Chart.js DataLabels plugin:

Javascript

var myPieChart = new Chart(ctx, {
    type: 'pie',
    data: {
        labels: ['A', 'B', 'C'],
        datasets: [{
            data: [30, 40, 30],
            backgroundColor: ['red', 'blue', 'green']
        }]
    },
    plugins: [{
        datalabels: {
            formatter: (value, ctx) => {
                let sum = 0;
                let dataArr = ctx.chart.data.datasets[0].data;
                dataArr.map(data => {
                    sum += data;
                });
                let percentage = (value * 100 / sum).toFixed(2) + "%";
                return percentage;
            },
            color: '#fff'
        }
    }]
});

In this code snippet, we create a pie chart with three data points ('A', 'B', 'C') and corresponding values. We then configure the `datalabels` plugin to calculate the percentage value for each chart slice based on the total sum of the data points and display it in white color.

You can further customize the appearance of the percentage labels by modifying the `formatter` function and adjusting the styling properties such as `color`, `font`, `offset`, and more within the `datalabels` object.

By following these steps and customizing the data labels using the Chart.js DataLabels plugin, you can enhance the readability and visual appeal of your pie charts by showing percentage values directly within the chart slices.

We hope this tutorial has been helpful in guiding you on how to display percentage values in pie pieces using Chart.js DataLabels plugin. Experiment with different configurations and make your pie charts more informative and engaging for your audience!