Skip to content
Advertisement

chart.js LIne Graphs: Fill area above line as opposed to below and to the right

I have a chart.js which displays two different lines, on which will always be positive and one which will always be negative.

I want to visualize the area between both lines and a value of 0 on the y axis and therefore want to fill in below the the positive line and above the negative line both ending at 0. Chart.js however always fills in the line to the bottom right of a given line as far as I cant tell.

Correct Behaviour: (from chartist.js)

Graph with correct Behavior

Incorrect Behavior (from chart.js)

Graph with incorrect Behavior

Does anyone know if it is possible to achieve something similar to the look of the first graph with chart.js?

edits:

I am using chart.js through it’s ember plugin

{{ember-chart type='Line' data=dataPanelService.chartData width=500 height=600}}

so I am only passing in chartData. It should be using the default options.

The chart data in the dataPanelService:

chartData: {
  labels: ["9 /15 /15", "9 /28 /15", "10 /5 /15", "10 /13 /15", "10 /19       /15", "10 /30 /15", "11 /15 /15"],
  datasets: {
     {
        fillColor: "#FF1717", 
        pointColor: "#da3e2f", 
        data: [200000, 180000, 150000, 110000, 60000, 0, 0]
     },
     {
        fillColor: "#4575b5", 
        pointColor: "#1C57A8", 
        data: [-300000, -300000, -300000, -150000, -150000, -20000, 0]
     },
  }
}

Advertisement

Answer

Filling / Coloring the Area between Lines

Just extend the chart to write your own fill logic.

Note that the animation is a bit weird because of the filling logic. It would be easier to turn off the animation to fix this, or you could try a variation of https://stackoverflow.com/a/33932975/360067 to animate from the 0 line.


Preview

enter image description here


Script

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

        var ctx = this.chart.ctx;
        var scale = this.scale;

        ctx.save();

        ctx.fillStyle = this.datasets[0].fillColor;
        ctx.beginPath();
        ctx.moveTo(scale.calculateX(0), scale.calculateY(0))
        this.datasets[0].points.forEach(function (point) {
            ctx.lineTo(point.x, point.y);
        })
        ctx.closePath();
        ctx.fill();

        ctx.fillStyle = this.datasets[1].fillColor;
        ctx.beginPath();
        ctx.moveTo(scale.calculateX(0), scale.calculateY(0))
        this.datasets[1].points.forEach(function (point) {
            ctx.lineTo(point.x, point.y);
        })
        ctx.closePath();
        ctx.fill();

        ctx.restore();
    }
});

...

var myNewChart = new Chart(ctx).LineAlt(chartData, {
    bezierCurve: false,
    datasetFill: false
});

Fiddle – https://jsfiddle.net/fhxv0vL7/

Advertisement