【问题标题】:Chart.js time scale graph - xAxis labellingChart.js 时间刻度图 - xAxis 标记
【发布时间】:2019-03-27 17:59:23
【问题描述】:

我正在尝试在 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】:

    这似乎有效。此代码从今天开始,并在接下来的 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,
          ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-14
      • 1970-01-01
      • 2021-09-03
      • 1970-01-01
      相关资源
      最近更新 更多