How to display value after the bar using chart.js?

Member

by jerad , in category: Javascript , 9 months ago

How to display value after the bar using chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by haylee.mertz , 9 months ago

@jerad 

To display the value after the bar in a chart created using Chart.js, you can add a custom label callback function to the chart options.


Here is an example of how you can achieve this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['January', 'February', 'March', 'April', 'May'],
        datasets: [{
            label: 'Sales',
            data: [12, 19, 3, 5, 2],
            backgroundColor: 'rgba(255, 99, 132, 0.2)',
            borderColor: 'rgba(255, 99, 132, 1)',
            borderWidth: 1
        }]
    },
    options: {
        plugins: {
            datalabels: {
                anchor: 'end',
                align: 'end',
                formatter: function(value, context) {
                    return value;
                }
            }
        }
    }
});


In this example, we are using the datalabels plugin provided by Chart.js to display the value after the bar. The formatter function is used to format the value displayed after the bar. You can customize the formatting as needed based on your requirements.


Make sure to include the Chart.js library and the plugin script in your HTML file before implementing this code.