How to add an empty data point to a linechart on Chart.js?

16,943

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.

Share:
16,943
TheBigDoubleA
Author by

TheBigDoubleA

Updated on June 07, 2022

Comments

  • TheBigDoubleA
    TheBigDoubleA almost 2 years

    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?