首页 > 解决方案 > 对 Y 轴 + 图表 Js 上的时间单位进行排序

问题描述

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

在此处输入图像描述

但是,如您所见,我的 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/

标签: chart.js

解决方案


Chart.js 2.8.0增加了reverse对 time scales的支持,尽管除了发行说明之外似乎没有记录在任何地方。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>


推荐阅读