[Chartjs]-How to add an empty data point to a linechart on Chart.js?

15πŸ‘

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:

Chart with spanGaps = false

Chart with spanGaps = true
Chart with spangaps = true

6πŸ‘

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/

Edit Aug 2016

This now works out of box without the need for an extension, just be using the null as a data point.

Leave a comment