首页 > 解决方案 > 使用 Chart.js 无法正确呈现具有时间序列数据的条形图

问题描述

我正在尝试使用时间序列数据渲染条形图,但它没有正确渲染,我在堆栈条之间得到了空格,我已经注释掉了我通过 AJAX 调用从 Web 服务器接收到的示例数据。

在此处输入图像描述

这是我的代码:

  let config = {
    type: 'bar',
    labels: res['labels'],
    data: {
      datasets: [{
            label: "Success",
            data: _.map(res['success'], (obj) => { return { x: new Date(obj.x), y: obj.y}; }),
//            data: [{
//                x: new Date('2017-03-01'),
//                y: 1
//            }, {
//                x: new Date('2017-03-02'),
//                y: 2
//            }, {
//                x: new Date('2017-03-03'),
//                y: 3
//            }, {
//                x: new Date('2017-03-04'),
//                y: 4
//            }],
            backgroundColor: "green"
        }, {
            label: "Failure",
            data: _.map(res['failed'], (obj) => { return { x: new Date(obj.x), y: obj.y}; }),
//            data: [{
//                x: new Date('2017-03-01'),
//                y: 1
//            }, {
//                x: new Date('2017-03-02'),
//                y: 2
//            }, {
//                x: new Date('2017-03-03'),
//                y: 3
//            }, {
//                x: new Date('2017-03-04'),
//                y: 4
//            }],
            backgroundColor: "red"
        }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      legend: {
        display: false,
      },
      tooltips: {
          callbacks: {
              title: function(tooltipItem, data) {
                  const [month, year] = tooltipItem[0].label.split(',', 2);
                  return `${month}, ${year}`;
              }
          }
      },
      scales: {
        xAxes: [{
          type: "time",
          stacked: true,
          offset: true,
          categoryPercentage: 1.0,
          barPercentage: 1.0,
          barThickness: 20,
          maxBarThickness: 25,
          minBarLength: 50,
          gridLines: {
              offsetGridLines: true
          },
          time: {
            unit: 'day',
            round: 'day',
            displayFormats: {
              day: 'MMM D'
            }
          }
        }],
        yAxes: [{
          stacked: true,
          ticks: {
            beginAtZero: true
          }
        }]
      }
    }
  }

  let chartEl = $('.bart-activity-graph-canvas');
  return new Chart(chartEl, config);

- - - - - - - - - 更新 - - - - - - - - - -

解决方案:问题是因为我使用了 _.map() 函数,它不能保证在数组中的位置。

标签: javascriptchart.jschartjs-2.6.0

解决方案


推荐阅读