You have to move your data within a dataset
. If you take a look at the usage manual, a datasets
array is used. The “hint” for datasets within the docs for time is also not that obvious (See headline).
See the snippet below:
I just copied the basic usage example and inserted the data from your first attempt (+ added few labels)
UPDATE 18.03.2020
I’ve updated the snippet to use Chart.js 2.8.0
and added following code, as suggested in the comment by @Erik
options: {
scales: {
xAxes: [{
type: 'time'
}]
}
}
UPDATE 16.02.2021
As pointed out by @habib, the 2.9.4 version was throwing couple of errors. I guess that those were caused by missing dependency (moment.js). See:
Note: starting v2.8, Moment.js is an optional dependency for Chart.js and Chart.min.js. In order to use the time scale with Moment.js, you need to make sure Moment.js is fully loaded before requiring Chart.js. You can either use a shim
Source
Therefore, I changed following things:
- Updated Chart.js to 2.9.4
- Added moment.js (2.29.1) as dependency
- Adjusted the time format to be ISO8601 compliant (As suggested by soiboi)
var ctx = document.getElementById("examChart").getContext("2d");
var myChart = new Chart(ctx, {
type: 'line',
options: {
scales: {
xAxes: [{
type: 'time',
}]
}
},
data: {
labels: ["2015-03-15T13:03:00Z", "2015-03-25T13:02:00Z", "2015-04-25T14:12:00Z"],
datasets: [{
label: 'Demo',
data: [{
t: '2015-03-15T13:03:00Z',
y: 12
},
{
t: '2015-03-25T13:02:00Z',
y: 21
},
{
t: '2015-04-25T14:12:00Z',
y: 32
}
],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js"></script>
<div class="container">
<canvas id="examChart"></canvas>
</div>