如何将小时和分钟数据输入chartJS

时间:2017-09-03 10:16:28

标签: javascript chart.js momentjs data-visualization

我正在尝试使用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提供数据标签吗?

1 个答案:

答案 0 :(得分:5)

您不能只将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>