Chart.js create line graph using dates in the x-axis that reflect real time intervals (not evenly distributed)

👍: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>

Leave a comment