[Chartjs]-Plot lap times with Chart.js from time strings

5👍

You can set the parser option to read the time values in the correct format.

 yAxes: [{
    type: 'time',
    time: {
      parser: 'm:s.SSS'
    }
  }]

Below is your sample as a snippet with the parser set:

const times = ["1:32.599", "1:32.300", "1:31.000"];
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ['1', '2', '3'], // list of races,
    datasets: [{
      label: "Best Lap",
      fill: false,
      data: times,
    }]
  },
  options: {
    scales: {
      yAxes: [{
        type: 'time',
        time: {
          parser: 'm:s.SSS',
          unit: 'seconds',
          unitStepSize: 5,
          min: '1:0.0',
          max: '2:0.0',
          displayFormats: {
            'seconds': 'm.s'
          }
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"></script>
<canvas id="myChart" width="200" height="200"></canvas>

However I’ve noticed that the min value is a the top of the y-axis and the reverse option doesn’t seem to work with a time axis. So if you prefer the max value at the top you have to reverse it yourself in the tick callback.

const times = ["1:32.599", "1:32.300", "1:31.000"];
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ['1', '2', '3'], // list of races,
    datasets: [{
      label: "Best Lap",
      fill: false,
      data: times,
    }]
  },
  options: {
    scales: {
      yAxes: [{
        type: 'time',
        time: {
          parser: 'm:s.SSS',
          unit: 'seconds',
          unitStepSize: 5,
          min: '1:0.0',
          max: '2:0.0',
          displayFormats: {
            'seconds': 'm.s'
          }
        },
        ticks: {
          callback: function(value, index, values) {
            //Ticks reverse does not work with time axes so we have to revert in this callback
            if (values[values.length - index] != undefined) {
              return moment(values[values.length - index].value).format('m.ss');
            }
          }
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"></script>
<canvas id="myChart" width="200" height="200"></canvas>

Leave a comment