如何将小时和分钟数据馈送到chartJS

roqulrg3  于 2023-06-22  发布在  Chart.js
关注(0)|答案(1)|浏览(170)

我正在尝试使用Chart.js制作折线图。我的数据是这样的:

var result = [
  { x: "18:00", y: "230" },
  { x: "19:00", y: "232" },
  { x: "20:00", y: "236" },
  { x: "22:00", y: "228" }
];

其中x表示时间,用小时和分钟表示。我这样输入数据

var ctx = document.getElementById("myChart").getContext('2d');
    var myChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: ["00:00","01:00","02:00","03:00","04:00","05:00","06:00","07:00","08:00","09:00","10:00","11:00","12:00","13:00","14:00","15:00","16:00","17:00","18:00","19:00","20:00","21:00","22:00","23:00","24:00"],
            datasets: [{
                label: 'Voltage Fluctuation',
                data: result,
                borderWidth: 1
            }]
        },
        options: {
            scales: {
                xAxes: [{
                    type: 'time',
                    position: 'bottom',
                    unit: 'minute',
        time: {
          displayFormats: {
            hour: 'HH:mm'
          }
        }
      }],
    },
  }
});

我得到的是一张空的病历。我哪里做错了?我觉得我的标签做错了什么,因为他们没有显示在图表上,但我不明白为什么。有什么方法可以用momentjs来填充datalabels吗?

lawou6xi

lawou6xi1#

不能直接将result数组传递给data,因为它的格式不正确。data属性需要一个数字数组。因此,在将标签 (使用moment.js)result数组中的数据用于图表之前,您需要解析它们。
下面是如何从result数组中解析标签和数据并将其馈送到图表中:

var result = [{ x: "18:00", y: "230" }, { x: "19:00", y: "232" }, { x: "20:00", y: "236" }, { x: "22:00", y: "228" }];

// parse labels and data
var labels = result.map(e => moment(e.x, 'HH:mm'));
var data = result.map(e => +e.y);

var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
   type: 'line',
   data: {
      labels: labels,
      datasets: [{
         label: 'Voltage Fluctuation',
         data: data,
         borderWidth: 1
      }]
   },
   options: {
      scales: {
         xAxes: [{
            type: 'time',
            time: {
               unit: 'hour',
               displayFormats: {
                  hour: 'HH:mm'
               }
            }
         }]
      },
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="myChart"></canvas>

相关问题