简体   繁体   English

图表 JS 使用 addData 在 x 轴上添加标签

[英]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:我正在使用 Chart JS 构建一个动态折线图,并且我设法让 function 工作,将数据标签附加到 x 轴的末尾,如下所示:

addData gif添加数据 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.我无法弄清楚的是如何更改 function 以便 function 将数据标签附加到 x 轴的前面,而不是将它们附加到 x 轴的末尾(根据 gif)。 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.基本上在执行时,function 将新数据从数组添加到 x 轴的开头,而不是当前 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".在加载第一个 label 之前添加到 x 轴的附加标签,即“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!我很茫然,所以任何帮助将不胜感激!

Instead of using Array.push() , you should use Array.unshift() as follows:而不是使用Array.push() ,您应该使用Array.unshift()如下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM