Show Legend Text even when DataPoints are not present in a DataSeries - CanvasJS JavaScript Charts
Show Legend Text even when DataPoints are not present in a DataSeries - CanvasJS JavaScript Charts
by canvasjs
HTML
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<br/><!-- Just so that JSFiddle's Result label doesn't overlap the Chart -->
<div id="chartContainer" style="height: 360px; width: 100%;"></div>
JavaScript
var chart = new CanvasJS.Chart("chartContainer",{
title:{
text: "Show Legend even when DataPoints is empty"
},
data: [{
type: "line",
showInLegend: true,
dataPoints: []
},
{
type: "line",
showInLegend: true,
dataPoints: [
{ x: new Date(2017, 6, 3), y: 8 },
{ x: new Date(2017, 6, 4), y: 7 },
{ x: new Date(2017, 6, 5), y: 7 },
{ x: new Date(2017, 6, 6), y: 6 },
{ x: new Date(2017, 6, 7), y: 10 },
{ x: new Date(2017, 6, 8), y: 9 },
{ x: new Date(2017, 6, 9), y: 8 }
]
}
]
});
addOrRemoveDatapoints(chart);
chart.render();
function addOrRemoveDatapoints(chart) {
for(var i = 0; i < chart.options.data.length; i++) {
if(chart.options.data[i].dataPoints.length < 1){
if( i > 0 && i < chart.options.data.length){
chart.options.data[i].dataPoints.push({ x: chart.options.data[0].dataPoints[0].x, y: null, dummyData: true});
}
else if(i != chart.options.data.length){
chart.options.data[i].dataPoints.push({ x: chart.options.data[chart.options.data.length-1].dataPoints[0].x, y: null, dummyData: true});
}
}
for(var j = 0; j < chart.options.data[i].dataPoints.length; j++){
if(jQuery.isEmptyObject(chart.options.data[i].dataPoints[j]) && chart.options.data[i].dataPoints.length > 1 && chart.options.data[i].dataPoints[j].dummyData ){
chart.options.data[i].dataPoints.splice(j, 1);
}
}
}
}