Chartjs-How to draw 2d line time plot with chart.js

1πŸ‘

βœ…

To make your code work, you could use a scatter chart and add the options showLine: true to each dataset.

In order to obtain formatted labels for each day, you need to define the x-axis as a time cartesian axis by adding the following configuration to chart options.

scales: {
  xAxes: [{
    type: 'time',
    time: {
      unit: 'day',
      tooltipFormat: 'MMM DD'
    }
  }] 
}

Please note that Chart.js internally uses Moment.js for the functionality of the time axis. Therefore you should use the bundled version of Chart.js that includes Moment.js in a single file.

When it comes to also show the labels in the tooltip, add the following to the chart options.

tooltips: {
  mode: 'point',
  callbacks: {
    title: (tooltipItem, data) => data.datasets[tooltipItem[0].datasetIndex].label
  }
}

Please take a look at your amended CodePen.

Leave a comment