[Chartjs]-Chart data on 24hr X axis using recharts, chart.js, I don't mind what

2๐Ÿ‘

โœ…

You can do this quite easily with Chart.js by using the built-in time axis.

The trick is to supply the correct configuration values to the x-axis:

  • unit: hour โ€“ the ticks are based on the hour.
  • stepSize: 3 โ€“ the ticks are shown for every third hour.
  • min: "2015-06-12T00:00" โ€“ the ticks start from the beginning of the day.
  • max: "2015-06-13T00:00" โ€“ the ticks end at the beginning of the next day.

As long as the dataset you provide is correctly sorted (in sequential datetime order) then you should get a result like in this snippet:

new Chart(document.getElementById("chart"), {
  type: "line",
  data: {
    datasets: [{
      data: [{
          t: "2015-06-12T00:49:50+00:00",
          y: 85
        },
        {
          t: "2015-06-12T07:09:03+00:00",
          y: 77
        },
        {
          t: "2015-06-12T11:23:15+00:00",
          y: 58,
        },
        {
          t: "2015-06-12T16:00:58+00:00",
          y: 110
        },
        {
          t: "2015-06-12T19:35:01+00:00",
          y: 97
        },
        {
          t: "2015-06-12T21:15:50+00:00",
          y: 142
        }
      ]
    }]
  },
  options: {
    scales: {
      xAxes: [{
        type: "time",
        time: {
          unit: "hour",
          stepSize: 3,
          min: "2015-06-12T00:00",
          max: "2015-06-13T00:00",
          displayFormats: {
            hour: 'HH:mm'
          }
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>
<canvas id="chart"></canvas>

Leave a comment