0

我一直在研究时间刻度线图,并注意到当所有数据点足够接近时,xAxis 标签会自动转换为时间。我尝试了不同的 xAxis 时间单位,但没有成功。

这是一个简单的 codepen 示例,其中 xAxis 标签按小时显示。如果您将时刻更改为三月而不是四月,则 xAxis 标签按日期排列。有没有办法强制 xAxis 标签始终为日期和时间?

xAxes: [{
                    type: 'time',
                    time: {
                        parser: timeFormat,
                        // unit: 'day',
                        // unit: 'hour',
                        tooltipFormat: 'll HH:mm'
                    },

https://codepen.io/ccwakes/pen/abvzewW

谢谢

4

1 回答 1

0

您可以time.displayFormats根据Chart.js 文档中的显示格式使用属性。有关允许的格式字符串,请参阅Moment.js

time: {
  unit: 'hour',
  displayFormats: {
    hour: 'MMM DD HH:mm'
  },
  tooltipFormat: 'MMM DD HH:mm'
}

请在下面查看您修改后的代码。

new Chart(document.getElementById('canvas'), {
  type: 'line',
  data: {
    datasets: [{
      label: 'Dataset 1',
      backgroundColor: 'red',
      borderColor: 'red',
      fill: false,
      data: [
        { x: '2020-04-10 13:00', y: 60 }, 
        { x: '2020-04-12 06:00', y: 100 }, 
        { x: '2020-04-12 13:00', y: 5 }
      ],
    }, {
      label: 'Dataset 2',
      backgroundColor: 'blue',
      borderColor: 'blue',
      fill: false,
      data: [
        { x: '2020-04-10 13:00', y: 45 }, 
        { x: '2020-04-11 13:00', y: 65 }, 
        { x: '2020-04-12 06:00', y: 80 }, 
        { x: '2020-04-12 13:00', y: 65 }
      ]
    }]
  },
  options: {
    title: {
      text: 'Time Scale'
    },
    scales: {
      xAxes: [{
        type: 'time',
        time: {
          unit: 'hour',
          displayFormats: {
            hour: 'MMM DD HH:mm'
          },
          tooltipFormat: 'MMM DD HH:mm'
        },
        scaleLabel: {
          display: true,
          labelString: 'Date'
        }
      }],
      yAxes: [{
        display: true,
        scaleLabel: {
          display: true,
          labelString: 'Value'
        }
      }]
    },
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="canvas" height="90"></canvas>

于 2020-04-12T06:29:31.817 回答