-1

In short, my question is based on the following question:

Chart.js creating a line graph using dates

There are many examples in there that work, however, the time intervals in the x-axis will always have the same space between them [no matter the format used or the options specified].

Example: assume I have the following times in the x-axis (ignore the format):

12:04pm, 12:08pm, 12:12pm, 12:30pm

In this case, the graph will show the same gap length between [12:04pm -> 12:08pm] and [12:12pm -> 12:30pm] which is not ideal. I would like the gap lengths to reflect the real-life intervals (= the second spacing should be bigger than the first one).

Is this something possible to do with Chart.js? The original poster in the linked question concluded that this isn't a feature available in Chart.js, and I just want some sort of confirmation on this before I look into another graph library.

Ghadir
  • 507
  • 10
  • 21
  • I've found it's actually a feature that is supported by Chart.js. However, it needs some additional libraries for the implementation. Will post a complete solution once I manage to do it. – Ghadir Sep 08 '21 at 11:08

1 Answers1

2

You can achieve this by using a time axis, since chart.js v3 you will need to include an adapter for this:

var options = {
  type: 'line',
  data: {
    datasets: [{
      label: '# of Votes',
      data: [{
        x: new Date('09-08-2021 12:04'),
        y: 10
      }, {
        x: new Date('09-08-2021 12:08'),
        y: 15
      }, {
        x: new Date('09-08-2021 12:12'),
        y: 5
      }, {
        x: new Date('09-08-2021 12:30'),
        y: 8
      }],
      borderColor: 'pink'
    }]
  },
  options: {
    scales: {
      x: {
        type: 'time',
      }
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
</body>
LeeLenalee
  • 27,463
  • 6
  • 45
  • 69