简体   繁体   English

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

[英]Chart.js time scale graph - xAxis labelling

I'm trying to set my own labels on the xAxis however I'm not sure how to do it using the example code I found.我正在尝试在 xAxis 上设置我自己的标签,但是我不确定如何使用我找到的示例代码来做到这一点。

I want it to look like this essentially: https://www.chartjs.org/samples/latest/scales/time/line.html我希望它本质上是这样的: 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'
               }
            }
         }]
      },
   }
});

This seems to work.这似乎有效。 This code starts from today and adds in the next 10 days.此代码从今天开始,并在接下来的 10 天内添加。 You'll have to change date to whenever you want your start date to be as well as how many dates you need.您必须将日期更改为您希望开始日期以及您需要的日期数量。

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,
      ...

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

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