Search code snippets, questions, articles...

Show data values on charts created using chart.js

If you want to show data values labels on Chart.js, then you can use the chartjs-plugin-datalabels. This will display values on the chart on top or bottom of the chart area.
<canvas id="myChart" width="400" height="300"></canvas>


<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chartjs-plugin-datalabels.min.js"></script>

<script>
    Chart.register(ChartDataLabels);

    const ctx = document.getElementById('myChart').getContext('2d');
    const myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
            datasets: [{
                label: '# of Votes',
                data: [12, 19, 3, 5, 2, 3]
            }]
        },
        options: {
        maintainAspectRatio: false,
        responsive: true,
        plugins: {
            datalabels: { // This code is used to display data values
                anchor: 'end',
                align: 'top',
                formatter: Math.round,
                font: {
                    weight: 'bold',
                    size: 16
                }
            }
        }
        }
    });
</script>

Note that we have added chartjs-plugin-datalabels library to show data labels. You ca read about it here.

You can install the chartjs-plugin-datalabels using npm.

npm install chartjs-plugin-datalabels --save

And import the module in you js file

import {Chart} from 'chart.js';
import ChartDataLabels from 'chartjs-plugin-datalabels';

Or, you can add the script file for chartjs-plugin-datalabels from CDN also.

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chartjs-plugin-datalabels.min.js"></script>

After adding the additional plugin we also need to register it to Chart.js library. To register it globally for all charts or specifically to one chart, you can use the below code.

//To register it globally to all charts
Chart.register(ChartDataLabels);

// To register it for specific charts only
var chart = new Chart(ctx, {
  plugins: [ChartDataLabels],
  type: 'bar',
  data: { ... },
  options: { ... }
})

The code that we use in options to display data values ion Chart.js is as below.

options: {
    plugins: {
        datalabels: {
            anchor: 'end',
            align: 'top',
            formatter: Math.round,
            font: {
                weight: 'bold',
                size: 16
            }
        }
    }
}

The Live demo for showing data values on Chart.js can be found below.

Was this helpful?
0 Comments