Open In App

How to Show Labels on Pie Chart in ChartJS ?

Last Updated : 26 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Pie charts are an attractive way to represent data in an easy-to-understand manner. In the pie chart, the labels are very useful because, with the help of the labels, we can understand what type of data is represented in the chart.

Below are the different approaches to show labels on a pie chart:

Using plugins

  • Set up the basic HTML and CSS structure.
  • Include the Chart.js CDN and the datalabels plugin using <script> tags.
  • Create a new Chart object with the context, specifying the chart type as pie.
  • After that define the data for the chart, and include labels and corresponding values.
  • Then enable the datalabels plugin to display labels on the chart, otherwise, your chart will not be displayed.

Example: The below example uses datalabels plugin to show labels on pie chart.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
"width=device-width, initial-scale=1.0">
    <title>Pie Chart with Labels</title>
    <script src=
"https://cdn.jsdelivr.net/npm/chart.js">
    </script>
    <script src=
"https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels">
    </script>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma,
                Geneva, Verdana, sans-serif;
            background-color: #f5f5f5;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            padding: 20px;
        }

        .container {
            max-width: 800px;
            width: 100%;
            background-color: #fff;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
            text-align: center;
        }

        h1 {
            color: #e74c3c;
            margin-bottom: 20px;
        }

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

<body>
    <div class="container">
        <h1>
            Show the labels on Pie
            chart in Chart.js
        </h1>
        <canvas id="myPieChart" width="400" height="400">
        </canvas>
    </div>
    <script>
        document.addEventListener
            ("DOMContentLoaded", function () {
                const ctx = document.getElementById
                    ('myPieChart').getContext('2d');
                const myPieChart = new Chart(ctx, {
                    type: 'pie',
                    data: {
                        labels:
                            ['Red', 'Blue', 'Yellow',
                                'Green', 'Purple', 'Orange'],
                        datasets: [{
                            label: '# of Votes',
                            data: [12, 19, 3, 5, 2, 3],
                            backgroundColor: [
                                'red',
                                'blue',
                                'yellow',
                                'green',
                                'purple',
                                'orange'
                            ],
                            borderColor: [
                                'rgba(255, 99, 132, 1)',
                                'rgba(54, 162, 235, 1)',
                                'rgba(255, 206, 86, 1)',
                                'rgba(75, 192, 192, 1)',
                                'rgba(153, 102, 255, 1)',
                                'rgba(255, 159, 64, 1)'
                            ],
                            borderWidth: 1
                        }]
                    },
                    options: {
                        plugins: {
                            datalabels: {
                                color: 'white',
                                font: {
                                    size: 14,
                                    weight: 'bold'
                                },
                                formatter: (value, ctx) => {
                                    return ctx.chart.data.
                                        labels[ctx.dataIndex] + ': ' + value;
                                }
                            }
                        }
                    }
                });
            });
    </script>
</body>

</html>

Output:

pi-chart

Output : Using plugins

Using Looltip Label

  • At first set up the basic HTML and CSS structure .
  • After that create a canvas element where the Pie chart will be rendered.
  • Then add options to the chart configuration and inside the options object, define the tooltips property.
  • And the tooltips take’s a callback so inside the tooltips object, define the callbacks property then define the label function to customize the tooltip label.

Syntax:

new Chart(ctx, {
type: "pie",
data: {},
options: {
tooltip: {
callbacks:{
// Tooltip config options
},
},
},
});

Example: The below example shows the implementation of above-explained approach.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
"width=device-width, initial-scale=1.0">
    <title>
        Pie Chart with Labels
    </title>
    <script src=
"https://cdn.jsdelivr.net/npm/chart.js">
    </script>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma,
                Geneva, Verdana, sans-serif;
            background-color: #f5f5f5;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            padding: 20px;
        }

        .container {
            max-width: 800px;
            width: 100%;
            background-color: #fff;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
            text-align: center;
        }

        h1 {
            color: #e74c3c;
            margin-bottom: 20px;
        }

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

<body>
    <div class="container">
        <h1>
            Show the labels on Pie
            chart in Chart.js
        </h1>
        <canvas id="myPieChart" width="400" 
            height="400">
        </canvas>
    </div>
    <script>
        document.addEventListener
            ("DOMContentLoaded", function () {
                let ctx = document.getElementById
                    ('myPieChart').getContext('2d');
                let myPieChart = new Chart(ctx, {
                    type: 'pie',
                    data: {
                        labels:
                            ['Red', 'Blue', 'Yellow',
                                'Green', 'Purple', 'Orange'],
                        datasets: [{
                            label: '# of Votes',
                            data: [12, 19, 3, 5, 2, 3],
                            backgroundColor: [
                                'red',
                                'blue',
                                'yellow',
                                'green',
                                'purple',
                                'orange'
                            ],
                            borderColor: [
                                'rgba(255, 99, 132, 1)',
                                'rgba(54, 162, 235, 1)',
                                'rgba(255, 206, 86, 1)',
                                'rgba(75, 192, 192, 1)',
                                'rgba(153, 102, 255, 1)',
                                'rgba(255, 159, 64, 1)'
                            ],
                            borderWidth: 1
                        }]
                    },
                    options: {
                        tooltips: {
                            callbacks: {
                                label: function (tooltipItem, data) {
                                    let label = data.labels[tooltipItem.index];
                                    let value = data.datasets
                                    [tooltipItem.datasetIndex].
                                        data[tooltipItem.index];
                                    return label + ': ' + value;
                                }
                            }
                        }
                    }
                });
            });
    </script>
</body>

</html>

Output:

pi-chart

Output : Using Tooltip

Using Legend Option

  • Include the Chart.js library in the HTML file using a CDN.
  • Then define a new Chart() instance with the type set to ‘pie’.
  • After that use the legend option within the options object to display the legend.
  • For customize the legend labels using the labels.generateLabels callback function.
  • And inside the callback function, map over the chart data labels for generate legend labels based on the dataset values.

Example: The below example shows the implementation of above-explained approach.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
"width=device-width, initial-scale=1.0">
    <title>
        Pie Chart with Legend Labels
    </title>
    <script src=
"https://cdn.jsdelivr.net/npm/chart.js">
    </script>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, 
                Geneva, Verdana, sans-serif;
            background-color: #f5f5f5;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            padding: 20px;
        }

        .container {
            max-width: 800px;
            width: 100%;
            background-color: #fff;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
            text-align: center;
        }

        h1 {
            color: #e74c3c;
            margin-bottom: 20px;
        }

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

<body>
    <div class="container">
        <h1>
            Show the labels on Pie chart 
            using Legend in Chart.js
        </h1>
        <canvas id="myPieChart" width="400" 
            height="400">
        </canvas>
    </div>
    <script>
        document.addEventListener
            ("DOMContentLoaded", function () {
                var ctx = document.getElementById
                    ('myPieChart').getContext('2d');
                var myPieChart = new Chart(ctx, {
                    type: 'pie',
                    data: {
                        labels:
                            ['Red', 'Blue', 'Yellow',
                                'Green', 'Purple', 'Orange'],
                        datasets: [{
                            data: [12, 19, 3, 5, 2, 3],
                            backgroundColor: [
                                'red',
                                'blue',
                                'yellow',
                                'green',
                                'purple',
                                'orange'
                            ],
                            borderWidth: 1
                        }]
                    },
                    options: {
                        plugins: {
                            legend: {
                                display: true,
                                labels: {
                                    generateLabels: function (chart) {
                                        return chart.data.labels.
                                            map(function (label, i) {
                                                let backgroundColor = chart.data.
                                                    datasets[0].backgroundColor[i];
                                                return {
                                                    text: label + ': ' + chart.data.
                                                        datasets[0].data[i],
                                                    fillStyle: backgroundColor
                                                };
                                            });
                                    }
                                }
                            }
                        }
                    }
                });
            });
    </script>
</body>

</html>

Output:

fosiGIF



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads