Chartjs-Chart.js with plotting durations against dates

0👍

The following example illustrates how it can be done. I assume the y value '01:20' from your code to be of format '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>

Leave a comment