ArticleZip > Chart Js Show Labels On Pie Chart

Chart Js Show Labels On Pie Chart

Chart.js is a popular JavaScript library that allows developers to create interactive and visually appealing charts on web pages. One common question that many users have is how to display labels on a pie chart created using Chart.js. In this article, we will explore how you can easily show labels on your pie chart to provide additional context to your data visualization.

To display labels on a pie chart in Chart.js, you can utilize the 'datalabels' plugin. This plugin enables you to customize and position the labels according to your preferences. To get started, you need to include the datalabels plugin in your project.

First, you will need to download and include the plugin in your HTML file. You can do this by adding the following script tag:

Html

Next, you need to enable the datalabels plugin in your Chart.js configuration. You can do this by adding the 'plugins' option to your chart configuration and specifying the 'datalabels' property with the desired settings. Here is an example configuration that shows how to display labels on a pie chart:

Javascript

const config = {
    type: 'pie',
    data: {
        labels: ['Label 1', 'Label 2', 'Label 3'],
        datasets: [{
            data: [30, 40, 50],
            backgroundColor: ['red', 'green', 'blue']
        }]
    },
    options: {
        plugins: {
            datalabels: {
                color: '#fff',
                font: {
                    weight: 'bold'
                }
            }
        }
    }
};

In the above configuration, we have set the color of the labels to white and made the font weight bold. You can customize various aspects of the labels such as color, font size, position, and alignment to suit your design requirements.

Additionally, you can further fine-tune the appearance of the labels by specifying different options in the 'datalabels' property. Some common options include 'anchor' to control the position of the labels, 'align' to specify the text alignment, and 'offset' to adjust the distance between the labels and the chart elements.

Once you have configured the datalabels plugin to your liking, you can render the pie chart with labels by creating a new Chart.js instance and passing the configuration object as shown in the example above.

By following these simple steps, you can enhance your pie charts created with Chart.js by displaying informative labels that provide valuable insights into your data. Experiment with different configurations and settings to create visually stunning and informative data visualizations for your web projects. Happy charting!

×