Reputation: 452
I'm trying to add empty data points throughout a line chart using Chart.js. I have this:
var data = {
labels: [
"1","2","3","4","5","6","7","8","9","10"
],
datasets: [
{
label: "Traffic",
data: null,null,20,40,null,null,null,10,20,null
}
]
};
The problem is that the linechart only recognizes the first two "nulls" as being empty data points and doesn't display them. However, for the nulls that come after, a line (connecting the previous and next valid datapoint) is shown, which makes it seem as if the "null"-datapoints actually exist. Is there a way to NOT display null-values in linecharts? (Similar to what Canvas.js offer: http://canvasjs.com/docs/charts/basics-of-creating-html5-chart/empty-null-data-points-chart/)
I read through the Chart.js documentation and stackoverflow but could not find an answer. Can anyone help me?
Upvotes: 9
Views: 19185
Reputation:
I read line documentation and found a boolean option which is called spanGaps
Here's a piece of code, which i used to display this:
{
'type': 'line',
'data': {
'labels': [1, 2, 3, 4, 5],
'datasets': [{
'label': 'example',
'data': [4, 1, null, 3],
// These are style properties, there is no need to copy them
'borderColor': 'rgba(255,99,132,1)',
'borderWidth': 1,
'fill': false,
tension: 0.2,
}]
},
'options': {
spanGaps: true // this is the property I found
}
}
Chart with spanGaps = false
:
Upvotes: 16
Reputation: 41075
Posting the summary of the answer at Line ChartJS empty / null values doesn't break the line WITH (slight) corrections for the question above
Extend the line chart
Chart.types.Line.extend({
name: "LineAlt",
draw: function () {
Chart.types.Line.prototype.draw.apply(this, arguments);
// now draw the segments
var ctx = this.chart.ctx
this.datasets.forEach(function (dataset) {
ctx.strokeStyle = dataset.strokeColor
var previousPoint = {
value: null
};
dataset.points.forEach(function (point) {
if (previousPoint.value !== null && point.value !== null) {
ctx.beginPath();
ctx.moveTo(previousPoint.x, previousPoint.y);
ctx.lineTo(point.x, point.y);
ctx.stroke();
}
previousPoint = point;
})
})
}
});
You have to call the LineAlt thus
var myLineChart = new Chart(ctx).LineAlt(data, {
datasetStrokeWidth: 0.01,
datasetFill: false,
pointDotRadius : 2,
pointDotStrokeWidth: 3
});
Other changes made for your question - data should be an array and not a comma separated set of values value
Fiddle - http://jsfiddle.net/zu3p2nky/
This now works out of box without the need for an extension, just be using the null
as a data point.
Upvotes: 6