Chart.js,根据日期绘制持续时间

问题描述 投票:0回答:1

我正在尝试创建一个图表,在x轴上带有日期(MMMM DD, YYYY),在y轴上带有持续时间(h:mm:ss)。以下代码支持日期(x),但不支持持续时间(y)。

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: [moment("2009-04-11").format('MMMM DD, YYYY')],
        datasets: [{
            data: [{
                x: "2009-04-11",
                y: "01:20"
            }],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
            type: 'time',
                time: {
                    unit: 'minute'
                }
            }]
        }
    }
});
javascript graph chart.js
1个回答
0
投票

以下示例说明了如何完成此操作。我假设您代码中的y'01:20'的格式为'HH:mm'

const data = [
  { x: '2009-04-11', y: '01:20' },
  { x: '2009-05-02', y: '01:40' },
  { x: '2009-05-18', y: '01:10' }
];

new Chart(document.getElementById('myChart'), {
  type: 'line',
  data: {
    datasets: [{
      label: 'My Dataset',
      data: data.map(o => ({ x: o.x, y: moment.duration(o.y) })),
      backgroundColor: 'rgba(255, 99, 132, 0.2)',
      borderColor: 'rgba(255, 99, 132, 1)',
      borderWidth: 1
    }]
  },
  options: {
    tooltips: {
      callbacks: {       
        label: (tooltipItem, data) => moment.utc(data.labels[tooltipItem.index]).format('HH:mm')
      }
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true,
          stepSize: 1_200_000,
          callback: v => moment.utc(v).format('HH:mm')
        }        
      }],
      xAxes: [{
        type: 'time',        
        time: {
          unit: 'days',
          displayFormats: {
            days: 'MMMM DD, YYYY'
          }
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.3.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="90"></canvas>
© www.soinside.com 2019 - 2024. All rights reserved.