[Chartjs]-How can I format chart.js data labels while using chart.js datalabels plugin?

1👍

Found your issue, you are defining the options block a second time after your plugins section, this overrides the earlyer options block as there are no duplicate keys allowed in js objects, so if you change your config to this it will work:

async function setup() {
    var ctx = document.getElementById('myChart').getContext('2d');
    var poll = await getData();
    var myChart = new Chart(ctx, {
        type: 'horizontalBar',
        data: {
            labels: poll.years,
            datasets: [{
                label: 'how many people (%)',
                data: poll.vals,
                backgroundColor: [
                    '#cd0000',
                    '#eb7d44',
                    '#70AA5B',
                    '#CAF0FD',
                    '#134D85',
                ],
            }]
        },
        options: {
            scaleShowLabels: false,
            plugins: {
                datalabels: {
                    align: 'end',
                    color: 'red',
                }
            },
            layout: {
                padding: {
                    left: 0,
                    right: 0,
                    top: 8,
                    bottom: 0
                }
            },
            responsive: true,
            title: {
                display: false
            },
            legend: {
                display: true,
                position: 'top',
                usePointStyle: true,
                padding: 1,
                labels: {
                    boxWidth: 15
                }
            },
            scales: {
                yAxes: [{
                    ticks: {
                        display: false,
                        fontColor: '#ffffff',
                        zeroLineColor: '#ffffff'
                    }
                }],
                xAxes: [{
                    ticks: {
                        display: false
                    },
                }],
            }
        },
        plugins: [ChartDataLabels],
    });
}

Leave a comment