How to reverse chart.js label order?

by filiberto , in category: Javascript , 9 months ago

How to reverse chart.js label order?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raphael_tillman , 5 months ago

@filiberto 

To reverse the label order in a chart.js chart, you can simply reverse the array of labels that you pass to the chart.js options when creating the chart. Here's an example using a bar chart:

 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
26
27
28
29
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['January', 'February', 'March', 'April', 'May', 'June'],
        datasets: [{
            label: 'Sales',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: 'rgba(255, 99, 132, 0.2)',
            borderColor: 'rgba(255, 99, 132, 1)',
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }]
        }
    }
});

// Reverse the labels array
myChart.data.labels.reverse();

// Update the chart
myChart.update();


In this example, we simply call the reverse() method on the labels array of the chart data, and then call the update() method on the chart object to redraw the chart with the reversed labels.