Chartjs-Have shading begin at 0 but not scale

1👍

You can do this by hooking into the draw function of the first point (because you are basically closing off the path drawn by the line to do the fill) and using the y = 0 points to close off the path, like so.

Chart.types.Line.extend({
    name: "LineAlt",
    initialize: function (data) {
        Chart.types.Line.prototype.initialize.apply(this, arguments);

        var scale = this.scale;
        var firstDataset = this.datasets[0];
        var firstPoint = firstDataset.points[0];
        var min = (scale.min > 0 ? scale.min : (scale.max > 0 ? 0 : scale.max));

        originalDraw = firstPoint.draw;
        firstPoint.draw = function () {
            ctx.lineTo(firstDataset.points[firstDataset.points.length - 1].x, scale.calculateY(min));
            ctx.lineTo(firstDataset.points[0].x, scale.calculateY(min));
            ctx.fillStyle = firstDataset.fillColor;
            ctx.closePath();
            ctx.fill();

            return originalDraw.apply(this, arguments);
        }
    }
});

and you also have to turn off the datasetFill option (since we are doing it on our own)

var myChart = new Chart(ctx).LineAlt(data, {
    datasetFill: false
});

If you also want to move the x axis labels, the cleanest way to do it would be to turn off the current labels and just draw your own using the xLabels collection


Fiddle – http://jsfiddle.net/dnpo61tu/

Leave a comment