Open In App

How to Add Text Inside the Doughnut Chart Using Chart.js ?

Last Updated : 10 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Chart.JS, we have a doughnut chart to represent the data in slice forms for a more visual and attractive appearance. In the Doughnut Chart, we can place a custom text inside the doughnut chart to make the chart more informative and also help the readers understand the purpose or data doughnut chart. In this article, we will see two different approaches to adding text inside the doughnut chart.

Chart.js CDN Links:

<!--  jQuery CDN Link Version 2.1.1 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Chart.js Version 1.0.2 CDN Link - Supports Chart.js Extension -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>
<!-- jQuery CDN Link Version 3.6.1 -->
<script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"> </script>
<!-- Chart.js Version 4.0.1 CDN Link - Supports Chart.js Plugin -->
<script src= "https://cdn.jsdelivr.net/npm/chart.js@4.0.1/dist/chart.umd.min.js"> </script>

Approach 1: Using Chart.js Extension

In this approach, we are using the Chart.JS extension, where we have defined the extension name as “textInside” which overrides the ‘showTooltip‘ and ‘draw’ methods to manage the tooltip display and show custom text in the center of the doughnut chart.

Syntax:

Chart.types.[Type].extend({
// Extension here
});

Example: Below is the implementation of the above-discussed approach.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>Example 1</title>
    <!-- jQuery CDN -->
    <script src=
    </script>
    <!-- Chart.js CDN -->
    <script src=
    </script>
</head>
 
<body>
    <h1 style="color: green;">
        GeeksforGeeks
    </h1>
    <h3>
        Approach 1: Using
        Chart.JS Extension
    </h3>
    <canvas id="chart1"></canvas>
    <script>
        Chart.types.Doughnut.extend({
            name: "textInside",
            showTooltip: function () {
                this.chart.ctx.save();
                Chart.types.Doughnut.
                prototype.showTooltip.
                apply(this, arguments);
                this.chart.ctx.restore();
            },
            draw: function () {
                Chart.types.Doughnut.
                prototype.draw.
                apply(this, arguments);
                const width = this.chart.width;
                const height = this.chart.height;
                const fontSize = (height / 114).
                                    toFixed(2);
                this.chart.ctx.font = fontSize + "em Arial";
                this.chart.ctx.textBaseline = "middle";
                const text = "GFG";
                const textX = Math.round(
                    (width - this.chart.ctx.
                    measureText(text).width) / 2);
                const textY = height / 2;
                this.chart.ctx.
                fillText(text, textX, textY);
            }
        });
        const data = [{
            value: 20,
            color: "#FFCE56",
            label: "HTML"
        }, {
            value: 30,
            color: "#36A2EB",
            label: "React"
        }, {
            value: 15,
            color: "#FF6384",
            label: "Java"
        }, {
            value: 10,
            color: "#4CAF50",
            label: "Python"
        }, {
            value: 25,
            color: "#9C27B0",
            label: "JavaScript"
        }];
        const textChart = new Chart($('#chart1')[0].
        getContext('2d')).textInside(data, {
            responsive: true
        });
    </script>
</body>
 
</html>


Output:

Output1

Approach 2: Using Chart.JS Plugin

In this approach, we are using the Plugins to add the custom text as GeeksforGeeks inside the doughnut chart. We have defined the textInside plugin, which registers to the ‘afterDatasetsDraw‘ hook, which draws the GeeksforGeeks text at the center of the chart.

Syntax:

const options = {
plugins: {
legend: true,
textInside: true // Enable the custom plugin
}
};

Example: Below is the implementation of the above-discussed approach.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>Example 2</title>
    <script src=
    </script>
    <script src=
    </script>
</head>
<style>
    #chart1 {
        display: inline-block;
        position: relative;
        width: 50%;
    }
 
    element {
        display: block;
        box-sizing: border-box;
        height: 513.85px;
        width: 514.567px;
    }
</style>
 
<body>
    <h1 style="color: green;">
        GeeksforGeeks
    </h1>
    <h3>
        Approach 2: Using
        Chart.js Plugin
    </h3>
    <canvas id="chart1"
            style="display: block;
                   box-sizing: border-box;
                   height: 514px;
                   width: 514.667px;"
            width="772" height="771">
    </canvas>
    <script>
        const data = {
            labels:
            ["HTML", "React", "Java",
            "Python", "JavaScript"],
            datasets: [{
                data: [20, 30, 15, 10, 25],
                backgroundColor:
                ["#FFCE56", "#36A2EB", "#FF6384",
                "#4CAF50", "#9C27B0"]
            }]
        };
        const options = {
            plugins: {
                legend: true,
                tooltip: {
                    callbacks: {
                        label: function (tooltipItem, data) {
                            const label =
                            data.labels[tooltipItem.index] || '';
                            const value =
                            data.datasets[0].data[tooltipItem.index];
                            return `${label}: ${value}%`;
                        }
                    }
                },
                textInside: {
                    text: "GeeksforGeeks",
                    color: 'green',
                    fontSize: 28
                }
            }
        };
        Chart.register({
            id: 'textInside',
            afterDatasetsDraw: function (chart, _) {
                const ctx = chart.ctx;
                const width = chart.width;
                const height = chart.height;
                const fontSize = options.plugins.textInside.fontSize;
                ctx.font = fontSize + 'px Arial';
                ctx.fillStyle = options.plugins.textInside.color;
                ctx.textAlign = 'center';
                ctx.textBaseline = 'middle';
                const text = options.plugins.textInside.text;
                const textX = Math.round(width / 2);
                const textY = Math.round(height / 2);
                ctx.fillText(text, textX, textY);
            }
        });
        const textChart =
        new Chart(document.getElementById('chart1'), {
            type: 'doughnut',
            data: data,
            options: options,
            responsive: true
        });
    </script>
</body>
 
</html>


Output:

Output2



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads