'Data with x and y data, missing data are not taken into account
I have the following file
<!DOCTYPE html>
<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<body>
<canvas id="myChart" style="width:100%;max-width:600px"></canvas>
<script>
var xValues = ["2022-02-01","2022-02-02","2022-02-03","2022-02-04","2022-02-05"];
new Chart("myChart", {
type: "line",
data: {
labels: xValues,
datasets: [{
data: [{x:"2022-02-01",y:16},{x:"2022-02-02",y:16},{x:"2022-02-03",y:9},{x:"2022-02-05",y:11}],
borderColor: "red",
label:"data1",
fill: false
}]
},
options: {
legend: {display: true
}
}
});
</script>
As you can see there is no data for the date 2022-02-04 but the chart is drawing the next data at this date Is there away to get the correct chart, except adding the missing data ?
Solution 1:[1]
Assuming you want to stick to Chart.js version 2, you should change your x-axis into a time cartesian axis. Please note that Chart.js internally uses Moment.js for the functionality of the time axis. Therefore, you should use the bundled build of Chart.js that includes Moment.js in a single file.
Also don't define data.labels
since you provide the data as an array of data points (objects containing an x
and y
property each).
Please take a look at your amended code and see how it works.
new Chart("myChart", {
type: "line",
data: {
datasets: [{
data: [{x:"2022-02-01",y:16}, {x:"2022-02-02",y:16}, {x:"2022-02-03",y:9}, {x:"2022-02-05",y:11}],
borderColor: "red",
label:"data1",
fill: false
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day',
displayFormats: {
day: 'D MMM YYYY'
},
tooltipFormat: 'D MMM YYYY'
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.min.js"></script>
<canvas id="myChart"></canvas>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | uminder |