[Chartjs]-Time graphs chart.js

2👍

First you should omit labels but define your data as individual points, where each element has a t and an y property.

data: [
  { t: '4:45', y: 67 },
  { t: '6:12', y: 45 },
  { t: '7:33', y: 56 },
],

With above data, xAxes.time option will have to be defined as follows:

time: {
  parser: 'H:mm',
  unit: 'hour',
  stepSize: 1,
  displayFormats: {
    hour: 'H:mm'
  },
  tooltipFormat: 'H:mm'
},

Further you can define the xAxis.ticks option as follows:

ticks: {
  min: '0:00', 
  max: '8:00' 
}

As you already noticed, Chart.js internally uses Moment.js for the functionality of the time axis. Therefore you should use the bundled version of Chart.js that includes Moment.js in a single file.

Please take a look at the runnable code below and see how it works.

new Chart('myChart', {
  type: 'line',
  data: {
    datasets: [{
      label: 'My Dataset',      
      data: [
        { t: '4:45', y: 67 },
        { t: '6:12', y: 45 },
        { t: '7:33', y: 56 },
      ],
      borderColor: 'blue',
      fill: 'false',
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }],
      xAxes: [{
        type: 'time',
        time: {
          parser: 'H:mm',
          unit: 'hour',
          stepSize: 1,
          displayFormats: {
            hour: 'H:mm'
          },
          tooltipFormat: 'H:mm'
        },
        ticks: {
          min: '0:00', 
          max: '8:00' 
        }
      }]      
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.min.js"></script>
<canvas id="myChart" height="90"></canvas>

Leave a comment