Chart.js时间尺度图 - xAxis标签

问题描述 投票:1回答:1

我正在尝试在xAxis上设置我自己的标签但是我不知道如何使用我找到的示例代码来完成它。

我希望它看起来像这样:https://www.chartjs.org/samples/latest/scales/time/line.html

var result = [{ x: "00:01:53", y: "22" }, { x: "00:02:13", y: "45" }, { x: "00:02:43", y: "46" }, { x: "00:02:51", y: "51" }];
var result2 = [{ x: "00:01:52", y: "20" }, { x: "00:02:11", y: "42" }, { x: "00:02:41", y: "43" }, { x: "00:02:38", y: "50" }];

var labels = result.map(e => moment(e.x, 'h:mm:ss'));

var data = result.map(e => +e.y);
var data2 = result2.map(e => +e.y);

var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
   type: 'line',
   data: {
      labels: labels,
      datasets: [
          {
         label: 'g-force',
         data: data,
        borderColor: "#3e95cd",
         borderWidth: 1
      },
          {
         label: 'g-force',
         data: data2,
              borderColor: "#8e5ea2",
         borderWidth: 1
      }

      ],

   },
   options: {
      scales: {
         xAxes: [{
            type: 'time',
            time: {
               unit: 'second',
               displayFormats: {
                  second: 'h:mm:ss'
               }
            }
         }]
      },
   }
});
javascript chart.js
1个回答
1
投票

这似乎有效。此代码从今天开始,并在接下来的10天内添加。您需要将日期更改为您希望开始日期的时间以及所需的日期。

let labels = [];
var date = new Date();
var options = {
  month: "long",
  day: "numeric"
};

for (i = 0; i < 10; i++) {
    date.setDate(date.getDate() + i);
    labels.push(date.toLocaleDateString("en-US", options));
}


var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
   type: 'line',
   data: {
      labels: labels,
      ...
© www.soinside.com 2019 - 2024. All rights reserved.