在Y轴+图表Js上订购时间单位

时间:2019-07-01 11:54:02

标签: chart.js

我在Y轴上有时间,在X轴上有日期。我已经使用chart.js构建了图表,并且图表如下所示。

enter image description here

但是,正如您所看到的,我的Y轴方向相反。我不知道该如何解决。请协助。

这是我的js

var s1 = {
    label:'S1',
  borderColor: '#33b5e5',
  data: [
    { x: '2017-01-06 00:00:00', y: '2017-01-06 04:15:30' },
    { x: '2017-01-07 00:00:00', y: '2017-01-06 07:39:30' },
    { x: '2017-01-08 00:00:00', y: '2017-01-06 06:39:30' },
    { x: '2017-01-09 00:00:00', y: '2017-01-06 08:00:30' },
    { x: '2017-01-10 00:00:00', y: '2017-01-06 05:39:30' },
    { x: '2017-01-11 00:00:00', y: '2017-01-06 09:39:30' },
  ]
};
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
  type: 'line',

  data: { datasets: [s1] },
  options: {
     legend: {
        display: false
    },
    scales: {
      xAxes: [{
        type: 'time',
        weight : 0 ,
         time: {
           unit:'day'
          }
      }],
      yAxes: [{
        type: 'time',
        //type: 'linear',
        reverse: false,
         time: {
           unit:'hour'
          },
          ticks: {
                            beginAtZero:true
                        }
      }]
    }
  }
});

chart.canvas.parentNode.style.height = '380px';
chart.canvas.parentNode.style.width = '700px';

请在下面的链接中找到完整的代码段。 https://jsfiddle.net/sjabiulla/3d1tpwhy/1/

1 个答案:

答案 0 :(得分:1)

Chart.js 2.8.0 adds reverse support to time scales,尽管除release notes之外似乎没有任何记录。将reverse移到刻度配置中,它应该可以解决问题:

yAxes: [{
  ticks: {
    reverse: true,
    ...
  },
  ...
}]

这是一个可行的示例:

var s1 = {
  label: 'S1',
  borderColor: '#33b5e5',
  data: [{
      x: '2017-01-06 00:00:00',
      y: '2017-01-06 04:15:30'
    },
    {
      x: '2017-01-07 00:00:00',
      y: '2017-01-06 07:39:30'
    },
    {
      x: '2017-01-08 00:00:00',
      y: '2017-01-06 06:39:30'
    },
    {
      x: '2017-01-09 00:00:00',
      y: '2017-01-06 08:00:30'
    },
    {
      x: '2017-01-10 00:00:00',
      y: '2017-01-06 05:39:30'
    },
    {
      x: '2017-01-11 00:00:00',
      y: '2017-01-06 09:39:30'
    },
  ]
};
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [s1]
  },
  options: {
    legend: {
      display: false
    },
    scales: {
      xAxes: [{
        type: 'time',
        weight: 0,
        time: {
          unit: 'day'
        }
      }],
      yAxes: [{
        type: 'time',
        time: {
          unit: 'hour'
        },
        ticks: {
          reverse: true,
          beginAtZero: true
        }
      }]
    }
  }
});

chart.canvas.parentNode.style.height = '380px';
chart.canvas.parentNode.style.width = '700px';
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>
<canvas id="myChart"></canvas>