Chartjs-Display dataset values in bar chart.js

0👍

After hours of searching, I came across the datalabels plugin, which helped me achieve what I wanted.

import Chart from 'chart.js/auto';
import ChartDataLabels from 'chartjs-plugin-datalabels';

const data = [
    {
        name: 'Neighbour A',
        consumption: 720,
    },
    {
        name: 'Neighbour B',
        consumption: 745,
    },
    {
        name: 'Neighbour C',
        consumption: 917,
    },
    {
        name: 'My Household',
        consumption: 813,
    }
];

const main = () => {
    Chart.register(ChartDataLabels);

    new Chart(document.getElementById('consumptions'), {
        type: 'bar',
        data: {
            labels: data.map(m => m.name),
            datasets: [{
                label: 'Consumption',
                data: data.map(m => m.consumption),
                borderWidth: 1,
                barThickness: 40,
            }]
        },
        options: {
            plugins: {
                datalabels: {
                    rotation: -90,
                    formatter: function (value) {
                        return `${value} units`
                    }
                }
            },
        }
    })
};

main();

This plugin displays the dataset values in the bars and the rotation: -90 option rotates the values by 90 degrees anticlockwise, displaying them horizontally.

Leave a comment