Skip to content Skip to sidebar Skip to footer

Time Graphs Chart.js

I'm learning how to use chart.js and I want a graph that displays random values in different hours of the day (x axis) with format 'h?h:mm'. In the x axis I want a fixed step of on

Solution 1:

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.

newChart('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' 
        }
      }]      
    }
  }
});
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.min.js"></script><canvasid="myChart"height="90"></canvas>

Post a Comment for "Time Graphs Chart.js"