Add Missing Dates to Datapoints | CanvasJS JavaScript Charts
Add Missing Dates to Datapoints | CanvasJS JavaScript Charts
by canvasjs
HTML
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 360px; width: 100%;">
</div>
JavaScript
var chart = new CanvasJS.Chart("chartContainer", {
title:{
text: "Add Missing Dates to Datapoints"
},
axisX:{
title: "timeline"
},
axisY: {
title: "Downloads"
},
data: [
{
type: "area",
dataPoints: [//array
{ x: new Date(2012, 01, 1), y: 26},
{ x: new Date(2012, 01, 3), y: 38},
{ x: new Date(2012, 01, 4), y: 43},
{ x: new Date(2012, 01, 7), y: 29}
]
}
]
});
addMissingDps(chart);
chart.render();
function addMissingDps(chart) {
for(var i = 0; i < chart.options.data.length; i++) {
var newDps = [];
var dps = chart.options.data[i].dataPoints;
/* Find Missing Dates in an array - https://stackoverflow.com/a/40655233 */
var missingDates = dps.sort(function(a,b){
return Date.parse(a.x) - Date.parse(b.x);
}).reduce(function(hash){
return function(p,c){
var missingDaysNo = (Date.parse(c.x) - hash.prev) / (1000 * 3600 * 24);
if(hash.prev && missingDaysNo > 1) {
for(var i=1;i<missingDaysNo;i++)
p.push(new Date(hash.prev+i*(1000 * 3600 * 24)));
}
hash.prev = Date.parse(c.x);
return p;
};
}(Object.create(null)),[]);
/* Add missing dates to dataPoints */
for(var j = 0; j < missingDates.length; j++) {
dps.push({x: missingDates[j], y: 0})
}
/* Sort newly added dates - https://stackoverflow.com/a/10124053 */
dps.sort(function(a,b){
return Date.parse(a.x) - Date.parse(b.x);
});
}
}