You can use simple string categories to represent dates and temporal information, but by using an axis of the time type, you can parse, format, and generate temporal data. This allows greater flexibility and interactivity.
The time scale requires the moment.js library (momentjs.com). To use the time scale, you can either import the moment.js library or include the Chart.bundle.js library in your page. It's best to import moment.js since you might want to use other date and time functions. You can do that including by it in your page via CDN:
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js">
</script>
The data is usually configured using the point structure, where the x property is a Date and the y property is some quantitative value. You can also use the t property instead of x. Many standard date formats are parsed automatically. These are some valid data points for time:
{x: new Date(), y: 1} // now
{t: ‘20190224’, y: 2} // 2019-02-24
You can also include dates in a simple data object labels array:
new Chart("my-chart", {
type: "bar",
data: {
labels: [‘20190224’, ‘20190227’, ‘20190305’],
datasets: [...],
}
});
Here's a minimal example. This code uses the moment.js library to generate a list of dates using the moment.js library and creates a dataset of 10 dates. It uses the default values of all time-scale properties except axis.time.unit, which informs the unit that should be used:
const dataset = [];
let date = moment('20181120');
for(let i = 1; i <= 10; i+= 1) {
dataset.push({t: date, y: Math.random() * 10});
date = moment(date)
.add( Math.floor(Math.random() * 10)+1, 'days').calendar();
}
const dataObj = {
datasets: [{data: dataset, backgroundColor: 'hsla(290,100%,45%,.5)'}]
}
new Chart("my-chart", {
type: "bar",
data: dataObj,
options: {
legend: {display: false},
scales: {
xAxes: [{
type: 'time',
offset: true,
gridLines: { offsetGridLines: true },
time: {unit: 'day'}
}]
}
}
});
Offsets move bars and gridLines so that they stay within the chart. This is the default in bar charts with category scales, but not time scales. The result is shown here (Time/time-1.html). Note that the bars are not equally spaced, but the time intervals are. This is the default configuration, but you can change it, as we will see next: