Jimmy
Jimmy

Reputation: 29

Chart JS prepend labels to x-axis with addData

I'm building a dynamic line chart using Chart JS, and I've managed to get the function working that appends data labels to the end of the x-axis like this:

addData gif

What I cannot figure it out is how change the function so that instead of appending them to the end of the x-axis (per the gif), the function prepends the data labels to the front of the x-axis . Essentially when executed, the function adds the new data from the array to the beginning of the x-axis, not the end as per the current function.

Here's the code:

<button id="addData">Add Data</button>
document.getElementById('addData').addEventListener('click', function() {
            if (myChart.data.datasets.length > 0) {
                var year = YEARS[myChart.data.labels.length % YEARS.length];
                myChart.data.labels.push(year);

                myChart.data.datasets.forEach(function(dataset) {
                    dataset.data.push(myChart.data.datasets.data);
                });

                myChart.update();
            }
        });

The default labels on load.

var chartData = {
  labels: ["09/10", "10/11", "11/12", "12/13", "13/14", "14/15", "15/16", "16/17", "17/18", "18/19"]

The additional labels to add to the x-axis, prior to the fist label on load which is "09/10".

var YEARS = ["08/09", "07/08", "06/07", "05/06, "04/05"];

I'm at a loss, so any help would be greatly appreciated!

Upvotes: 0

Views: 417

Answers (1)

uminder
uminder

Reputation: 26150

Instead of using Array.push(), you should use Array.unshift() as follows:

myChart.data.labels.unshift(year);
myChart.data.datasets.forEach((dataset) => {
  dataset.data.unshift(myChart.data.datasets.data);
});

Upvotes: 2

Related Questions