Categories
Chart.js JavaScript

Chart.js Time Series Example

Plotting time series data with Chart.js is easy.

We can plot time series data with a line chart, which is a chart type that’s built into Chart.js

To use Chart.js, we first include it with a script tag by writing:

<script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js'></script>

<canvas id="timeSeriesChart" width="400" height="400"></canvas>

The chart will be rendered in the canvas element.

Then we create our chart by writing:

const ctx = document.getElementById('timeSeriesChart').getContext('2d');

const startDate = new Date(2020, 0, 1);
const labels = [];
for (let i = 0; i < 6; i++) {
  const date = moment(startDate).add(i, 'days').format('YYYY-MM-DD');
  labels.push(date.toString());
}

const chart = new Chart(ctx, {
  type: 'line',
  data: {
    labels,
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      borderWidth: 1
    }]
  },
  options: {}
});

The labels array has the labels on the x-axis. They are all dates.

data in datasets has the values on the y-axis.

label in datasets has the label for the legend.

After that code is written, we get:

https://thewebdev.info/wp-content/uploads/2020/04/timseries.png

We’ll see that the line chart has color-filled below the line.

We can disable that by changing the options.

To change the line color, we change the borderColor option in the datasets entry.

We can write:

const ctx = document.getElementById('timeSeriesChart').getContext('2d');

const startDate = new Date(2020, 0, 1);
const labels = [];
for (let i = 0; i < 6; i++) {
  const date = moment(startDate).add(i, 'days').format('YYYY-MM-DD');
  labels.push(date.toString());
}

const chart = new Chart(ctx, {
  type: 'line',
  data: {
    labels,
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      borderWidth: 5,
      fill: false,
      borderColor: 'green'
    }]
  },
  options: {}
});

With the borderWidth to change the thickness of the line, fill set to false to disable the fill color between the line and the x-axis, and borderColor set to 'green' to change the line to the color green.

Then we get:

https://thewebdev.info/wp-content/uploads/2020/04/greentimeseries.png

As we can see from the Chart.js time series example above, it doesn’t take much effort to display simple time-series data with it.