Chartjs-ChartJS fails to render horizontal bar chart for timeseries data

0👍

When using horizontalBar, you must make sure your yAxis is defined as type: 'time'. Your data must also reflect this and provide the data for the correct axis.

{ y: '2020-01-01T00:00:00', x: Math.random() * 20 }

This could look as follows:

<!DOCTYPE html>
<html>
  <head>
    <title>Line Chart</title>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.js"></script>
    <style>
      canvas {
        -moz-user-select: none;
        -webkit-user-select: none;
        -ms-user-select: none;
      }
    </style>
  </head>

  <body>
    <div style="height: 450px; width: 300px">
      <canvas id="canvas"></canvas>
    </div>
    <script>
      const config = {
        type: 'horizontalBar',
        options: {
          title: { text: 'Bar Chart', display: true },
          responsive: true,
          maintainAspectRatio: false,
          scales: {
            yAxes: [
              {
                offset: true,
                type: 'time'
              },
            ]
          },
        },
        data: {
          datasets: [
            {
              label: 'Label 1',
              borderColor: '#40407a',
              backgroundColor: '#d1ccc0',
              borderWidth: 3,
              data: [
                { y: '2020-01-01T00:00:00', x: Math.random() * 20 },
                { y: '2020-01-01T01:00:00', x: Math.random() * 20 },
                { y: '2020-01-01T01:20:00', x: Math.random() * 20 },
                { y: '2020-01-01T02:10:00', x: Math.random() * 20 },
                { y: '2020-01-01T02:35:00', x: Math.random() * 20 },
                { y: '2020-01-01T03:00:00', x: Math.random() * 20 },
              ],
            },
          ],
        },
      };

      window.onload = function() {
        var ctx = document.getElementById('canvas').getContext('2d');
        window.myLine = new Chart(ctx, config);
      };
    </script>
  </body>
</html>

Leave a comment