Categories
JavaScript Answers

How to Display Pie Chart Data Values of Each Slice in Chart.js and JavaScript?

Spread the love

To display pie chart data values of each slice in Chart.js and JavaScript, we can use the chartjs-plugin-labels plugin.

To use it, we write the following HTML:

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

<script src='https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js
'></script>

<canvas width='200' height='200'></canvas>

to add the script tags for Chart.js, the plugin, and the canvas for the chart.

Next, we write:

const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')

const data = {
  datasets: [{
    data: [
      11,
      16,
      7,
      3,
      14
    ],
    backgroundColor: [
      "#FF6384",
      "#4BC0C0",
      "#FFCE56",
      "#E7E9ED",
      "#36A2EB"
    ],
    label: 'My dataset' // for legend
  }],
  labels: [
    "Red",
    "Green",
    "Yellow",
    "Grey",
    "Blue"
  ]
};

new Chart(ctx, {
  type: 'pie',
  data,
  options: {
    plugins: {
      labels: {
        render: 'value',
        precision: 0,
        showZero: true,
        fontSize: 12,
        fontColor: '#fff',
        fontStyle: 'normal',
        fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
        textShadow: true,
        shadowOffsetX: -5,
        shadowOffsetY: 5,
        shadowColor: 'rgba(255,0,0,0.75)',
        arc: true,
        position: 'default',
        overlap: true,
        showActualPercentages: true,
        images: [{
          src: 'image.png',
          width: 16,
          height: 16
        }],
        outsidePadding: 4,
        textMargin: 4
      }
    }
  }
});

We have the data object with the chart data and the color of the slices stored in backgroundColor.

Then we have some options for the text in the plugins.labels property.

Options include fontColor , fontStyle , fontFamily , fontSize and more that will be shown in the pie slices.

Now each pie slice should have the number corresponding to the slice size in it.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *