have a look at my code here. I am getting the data from backend so I am not able to manipulate them any further. I got Chart.js as Scatter chart working, but the provided dates are parsed wrong 2020 becomes 1996 and so on.
Any idea how I get the x-axis formatted the right way?
var config = {
type: 'scatter',
data: {
datasets: [
{
label: "US Dates",
data: [
{x:2020-01-23,y:25.55,date:[2020,1,23]},
{x:2020-01-24,y:21.53,date:[2020,1,24]},
{x:2020-01-25,y:21.11,date:[2020,1,25]}
],
fill: false,
borderColor: 'red'
}
]
},
options: {
responsive: true,
title: {
display: true,
text: "Chart.js Time Scale"
},
scales: {
xAxes: [{
time: {
parser: 'YYYY-MM-DD',
tooltipFormat: 'll',
unit: 'month',
unitStepSize: 1,
},
scaleLabel: {
display: true,
labelString: 'Date'
}
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: 'value'
}
}]
}
}
};
window.onload = function () {
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx, config);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<body>
<div style="width:75%;">
<canvas id="canvas"></canvas>
</div>
And please ignore the "date" values within the data. This is just coming from the backend.
Thanks!
You simply need to put quotes around the x values, and also set the x-axis type to 'time', that should resolve the issue!
I updated the display formats to show nicer x-axis labels
displayFormats: { 'day': 'DD-MMM'}
I've also separated the input data into its own variable, if this looks like what is coming from your backend all should be good:
const inputData = [
{x:'2020-01-23',y:25.55,date:[2020,1,23]},
{x:'2020-01-24',y:21.53,date:[2020,1,24]},
{x:'2020-01-25',y:21.11,date:[2020,1,25]}
];
var config = {
type: 'scatter',
data: {
datasets: [
{
label: "US Dates",
data: inputData,
fill: false,
borderColor: 'red'
}
]
},
options: {
responsive: true,
title: {
display: true,
text: "Chart.js Time Scale"
},
scales: {
xAxes: [{
type: 'time',
time: {
parser: 'YYYY-MM-DD',
tooltipFormat: 'll',
unit: 'day',
unitStepSize: 1,
displayFormats: {
'day': 'DD-MMM',
}
},
scaleLabel: {
display: true,
labelString: 'Date'
}
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: 'value'
}
}]
}
}
};
window.onload = function () {
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx, config);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<body>
<div style="width:75%;">
<canvas id="canvas"></canvas>
</div>