Chart.js如何仅显示小时和新天

时间:2019-01-03 09:20:35

标签: javascript charts

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

但是由于我们有2天,所以无法查看图表中的日期切换。有什么办法可以让我们几个小时,然后在我们切换的那一天打勾?

类似的东西:

enter image description here

谢谢!

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'
               }
            }
         }]
      },
   }
});
<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>

1 个答案:

答案 0 :(得分: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
        },
    },
  }]
}

这会产生一个像follwong的x轴 This produces an x axis like this