Chart.js 小时刻度显示日期切换

Bap*_*ste 4 javascript chart.js

我有一个为期 2 天的日期数组,我只想显示几个小时。没问题。

但是由于我们有 2 天,因此无法在图表中看到日期切换。有没有办法在我们切换时有几个小时然后打勾?

类似的东西:

在此处输入图片说明

谢谢 !

var labels = ['2018-12-20 14:00', '2018-12-20 15:00', '2018-12-20 16:00', '2018-12-20 17:00', '2018-12-20 18:00', '2018-12-20 19:00', '2018-12-20 23:00', '2018-12-21 02:00', '2018-12-21 03:00', '2018-12-21 04:00', '2018-12-21 05:00', '2018-12-21 10:00'];
var data = [256,24,14,12,154,123,23,254,145,123,11,255];

var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
   type: 'line',
   data: {
      labels: labels,
      datasets: [{
         label: 'Tickets selling',
         data: data,
         borderWidth: 1
      }]
   },
   options: {
      scales: {
         xAxes: [{
            ticks: {
                autoSkip: true,
                maxTicksLimit: 20,
                maxRotation: 0,
            },
            type: 'time',
            time: {
               unit: 'hour',
               displayFormats: {
                  hour: 'HH:mm'
               }
            }
         }]
      },
   }
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas id="myChart"></canvas>
Run Code Online (Sandbox Code Playgroud)

小智 5

这可以使用 chartjs 中的主要刻度选项来完成。

scales: {
  xAxes: [{
    type: 'time',
    time: {
        unit: 'hour',
        stepSize: 3, // I'm using 3 hour intervals here
        tooltipFormat: 'HH:mm',
    },
    ticks: {
        major: {
           enabled: true, // <-- This is the key line
           fontStyle: 'bold', //You can also style these values differently
           fontSize: 14 //You can also style these values differently
        },
    },
  }]
}
Run Code Online (Sandbox Code Playgroud)

这会产生一个像 follwong 一样的 x 轴 这会产生一个像这样的 x 轴

  • 没想到一年后还有回复。直到今天我仍然遇到这个问题。“major”是正确的解决方案。从来不知道那个。谢谢 ! (2认同)