[Chartjs]-How to draw the X-axis (line at Y = 0) in Chart.js?

1👍

You can Use :

scales: {
    xAxes: [{
        gridLines: {
            zeroLineWidth: 3,
            zeroLineColor: "#2C292E",
        },

    }]
}

Blockquote

0👍

You can extend the chart to do both – draw the line and color the points

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

        this.datasets.forEach(function (dataset, i) {
            dataset.points.forEach(function (point) {
                // color points depending on value
                if (point.value < 0) {
                    // we set the colors from the data argument
                    point.fillColor = data.datasets[i].pointColor[0];
                } else {
                    point.fillColor = data.datasets[i].pointColor[1];
                }
                // we need this so that the points internal color is also updated - otherwise our set colors will disappear after a tooltip hover
                point.save();
            })
        })
    },
    draw: function () {
        Chart.types.Line.prototype.draw.apply(this, arguments);

        // draw y = 0 line
        var ctx = this.chart.ctx;
        var scale = this.scale;
        ctx.save();
        ctx.strokeStyle = '#ff0000';
        ctx.beginPath();
        ctx.moveTo(Math.round(scale.xScalePaddingLeft), scale.calculateY(0));
        ctx.lineTo(scale.width, scale.calculateY(0));
        ctx.stroke();
        ctx.restore();
    }
});

var data = {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [
        {
            label: "My First dataset",
            fillColor: "rgba(220,220,220,0.2)",
            strokeColor: "rgba(220,220,220,1)",
            // point color is a an array instead of a string
            pointColor: ["rgba(220,0,0,1)", "rgba(0,220,0,1)"],
            pointStrokeColor: "#fff",
            pointHighlightFill: "#fff",
            pointHighlightStroke: "rgba(220,220,220,1)",
            data: [65, 59, 80, 81, -56, -55, 40]
        }
    ]
};

var ctx = document.getElementById("myChart").getContext("2d");
// use our new chart type LineAlt
var myNewChart = new Chart(ctx).LineAlt(data);

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

Leave a comment