Open In App

How to Add Percentage and Value Datalabels in Pie Chart in ChartJS?

Last Updated : 20 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Chart.js is a popular JavaScript library that allows developers to create a variety of responsive and interactive charts with ease. One common requirement when working with pie charts is to display both the percentage and the actual value of each data segment directly on the chart. In this article, we’ll explore how to add percentage and value data labels in a pie chart of Chart.js.

 <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>

These are the following approaches:

Using chartjs-plugin-datalabels

In this approach, we are using the chartjs-plugin-datalabels plugin to display both percentages and value directly on the pie chart. The plugin's formatter function calculates the percentage for each slice and combines it with the value, displaying both within the chart in a user-friendly format.

<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>

Example: The below example will add percentage and value data labels in a pie chart using chartjs-plugin-datalabels.

HTML
<!DOCTYPE html>
<html>

<head>
    <title> Add percentage and value datalables</title>
    <script src=
"https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js">
    </script>
    <script src="
  https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels">
</script>
    <style>
        body {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
            margin: 0;
            font-family: Arial, sans-serif;
        }

        h1 {
            color: green;
        }

        canvas {
            max-width: 400px;
            max-height: 400px;
            width: 100%;
            height: auto;
        }
    </style>
</head>

<body>
    <h1>GeeksforGeeks</h1>
    <h3>Approach 1: Using chartjs-plugin-datalabels</h3>
    <canvas id="pieChart1"></canvas>

    <script>
        const data1 = {
            labels: ['Articles', 'Tutorials', 'Videos', 'Quizzes'],
            datasets: [{
                data: [300, 50, 100, 75],
                backgroundColor: ['#4caf50', '#f44336', '#ffeb3b', '#2196f3'],
                hoverOffset: 4
            }]
        };

        const config1 = {
            type: 'pie',
            data: data1,
            options: {
                responsive: true,
                plugins: {
                    datalabels: {
                        formatter: (value, context) => {
                            let percentage = (value / context.chart._metasets
                            [context.datasetIndex].total * 100)
                                .toFixed(2) + '%';
                            return percentage + '\n' + value;
                        },
                        color: '#fff',
                        font: {
                            size: 14,
                        }
                    }
                }
            },
            plugins: [ChartDataLabels]
        };

        const pieChart1 = new Chart(
            document.getElementById('pieChart1'),
            config1
        );
    </script>
</body>

</html>

Output:

Screenshot-2024-08-16-at-18-23-17-GeeksforGeeks---Pie-Chart-with-Datalabels
Approach 1: Output

Using Custom Labels with Built-in ChartJS Configuration

In this approach, we are using the built-in tooltip and custom label formatting options provided by Chart.js to display both percentage and value information. The label callback function within the tooltip calculates the percentage of each data slice and displays it along with the raw value when the user hovers over the chart.

Syntax:

options: {
plugins: {
tooltip: {
callbacks: {
label: function(context) {
// custom label
return customLabel;
}
}
}
}
}

Example: The below example will add percentage and value data labels in a pie chart using custom labels with built-in chart.js configuration.

HTML
<!DOCTYPE html>
<html>

<head>
    <title> Add percentage and value datalables</title>
    <script src=
"https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js">
    </script>
    <style>
        body {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
            margin: 0;
            font-family: Arial, sans-serif;
        }

        h1 {
            color: green;
        }

        canvas {
            max-width: 400px;
            max-height: 400px;
            width: 100%;
            height: auto;
        }
    </style>
</head>

<body>
    <h1>GeeksforGeeks</h1>
    <h3>Approach 2: Using Custom Labels with Built-in Chart.js Configuration</h3>
    <canvas id="pieChart2"></canvas>

    <script>
        const data2 = {
            labels: ['Courses', 'Articles', 'Practice', 'Jobs'],
            datasets: [{
                data: [200, 150, 100, 50],
                backgroundColor: ['#4caf50', '#ff9800', '#9c27b0', '#03a9f4'],
                hoverOffset: 4
            }]
        };

        const config2 = {
            type: 'pie',
            data: data2,
            options: {
                responsive: true,
                plugins: {
                    tooltip: {
                        callbacks: {
                            label: function (context) {
                                let label = context.label || '';
                                let value = context.raw || 0;
                                let total =
                                    context.dataset.data.
                                    reduce((acc, curr) => acc + curr, 0);
                                let percentage = (value / total * 100).toFixed(2) + '%';
                                return label + ': ' + value + ' (' + percentage + ')';
                            }
                        }
                    }
                }
            }
        };

        const pieChart2 = new Chart(
            document.getElementById('pieChart2'),
            config2
        );
    </script>
</body>

</html>

Output:


Next Article

Similar Reads