1👍
✅
The problem in your code is that the chart options
is nested inside the data
object and actually ignored by Chart.js. Move it up to the next hierarchically level. Otherwise the xAxis
definition looks just fine. There’s also no need for explicitly parsing the date as one comment suggests since it is in a format that can be parsed by Date
.
Alternatively to your xAxis
definition, you can do it the following simpler way, the default display format of unit: 'day'
is actually what you’re looking for ('MMM D'
).
xAxes: [{
type: 'time',
time: {
unit: 'day'
}
}]
See below simplified example:
const data = [
{"reading_time":"2020-02-10 22:38:48","value1":"1.10"},
{"reading_time":"2020-02-11 22:39:18","value1":"1.20"},
{"reading_time":"2020-02-12 22:39:49","value1":"1.40"},
{"reading_time":"2020-02-13 22:40:19","value1":"1.10"},
{"reading_time":"2020-02-14 22:40:49","value1":"1.20"},
{"reading_time":"2020-02-15 22:41:19","value1":"1.30"}
];
new Chart("mycanvas", {
type: 'line',
data: {
labels: data.map(o => o.reading_time ),
datasets: [{
label: "Value1",
fill: false,
borderColor: "rgba(59, 89, 152, 1)",
data: data.map(o => o.value1)
}],
},
options: {
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day'
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js"></script>
<canvas id="mycanvas" height="90"></canvas>
Source:stackexchange.com