图表未正确显示时间轴

时间:2020-09-02 16:52:44

标签: reactjs chart.js

我有一个utc时间戳列表,可以解析为ChartJS 2.9.3,该图无法显示x轴时间,并且数据也无法显示。

配置

let chartConfig = {
    type: "line",
    data: {
        labels: [],
        datasets: [
            {
                pointRadius: 0,
                data: [],
                backgroundColor: ['rgba(255, 99, 132, 0.2)'],
                borderColor: ['rgba(255,99,132,1)'],
                borderWidth: 1
            }
        ]
    },
    options: {
        responsive: true,
        animation: {
            duration: 0
        },
        hover: {
            animationDuration: 0
        },
        responsiveAnimationDuration: 0,
        legend: {
            display: false
        },
        scales: {
            xAxes: [{
                type: 'time',
                ticks: {
                    source: "data",
                    autoSkip: true,
                    maxTicksLimit: 20
                },
                time: {
                    parser: 'HH:mm:ss',
                    tooltipFormat: 'HH:mm:ss',
                    unit: 'minute',
                    unitStepSize: 5,
                    displayFormats: {
                        'second': 'ss A',
                        'minute': 'hh:mm A',
                        'hour': 'HH:mm A'
                    }
                }
            }],
            yAxes: [{
                ticks: {min: 0, max: 150, stepSize: 10 }
            }]
        }
    }
}

标签(x轴)

通过moment(timestamp).format("HH:mm:ss")

生成

[“ 22:02:30”,“ 22:03:00”,“ 22:03:30”,“ 22:4:00”,“ 22:05:00”。,“ 22:07: 00“,” 22:10:00“]

数据(y轴)

[60,78,89,100,120,45,55]

问题

enter image description here

1 个答案:

答案 0 :(得分:1)

我取得了您的代码,一切正常,如下所示。我唯一需要纠正的就是删除labels数组中的多余点。

new Chart('myChart', {
  type: "line",
  data: {
    labels: ["22:02:30", "22:03:00", "22:03:30", "22:4:00", "22:05:00", "22:07:00", "22:10:00"],
    datasets: [{
      pointRadius: 0,
      data: [60, 78, 89, 100, 120, 45, 55],
      backgroundColor: ['rgba(255, 99, 132, 0.2)'],
      borderColor: ['rgba(255,99,132,1)'],
      borderWidth: 1
    }]
  },
  options: {
    responsive: true,
    animation: {
      duration: 0
    },
    hover: {
      animationDuration: 0
    },
    responsiveAnimationDuration: 0,
    legend: {
      display: false
    },
    scales: {
      xAxes: [{
        type: 'time',
        ticks: {
          source: "data",
          autoSkip: true,
          maxTicksLimit: 20,
          minRotation: 30
        },
        time: {
          parser: 'HH:mm:ss',
          tooltipFormat: 'HH:mm:ss',
          unit: 'minute',
          unitStepSize: 5,
          displayFormats: {
            'minute': 'hh:mm:ss A'
          }
        }
      }],
      yAxes: [{
        ticks: {
          min: 0,
          max: 150,
          stepSize: 10
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart"></canvas>