Multiple fill colors for line chart

Hi,

I just want to know if it is possible to have multiple fill color on Line chart that only have one dataset?

I’m trying to create a line chart that will change the fill color whenever the value on Y-Axis becomes negative.

It should look like this:
capture

I can do multiple colors using 2 datasets but it will look like this:https://jsfiddle.net/mzborromeo/26hbaza4/ which is not what I want. I need only one dataset and all the positive values must have a blue green fill color and negatives will have red fill color. Will it be possible?

Thanks

Author: Fantashit

3 thoughts on “Multiple fill colors for line chart

  1. Found a way. In this example I’m using the option fill: 'origin' on my dataset:

        plugins: [{
            beforeRender: function (c, options) {
                var dataset = c.data.datasets[0];
                var yScale = c.scales['y-axis-0'];
                var yPos = yScale.getPixelForValue(0);
    
                var gradientFill = c.ctx.createLinearGradient(0, 0, 0, c.height);
                gradientFill.addColorStop(0, window.myColors.green);
                gradientFill.addColorStop(yPos / c.height - 0.01, window.myColors.green);
                gradientFill.addColorStop(yPos / c.height + 0.01, window.myColors.red);
                gradientFill.addColorStop(1, window.myColors.red);
    
                var model = c.data.datasets[0]._meta[Object.keys(dataset._meta)[0]].$filler.el._model;
                model.backgroundColor = gradientFill;
            }
        }]
    
  2. berosoboy code wasn’t working for me on chart.js 2.5.0, I had to change it for:

    plugins: [{
            beforeRender: function (x, options) {
            		var c = x.chart
                var dataset = x.data.datasets[0];
                var yScale = x.scales['y-axis-0'];
                var yPos = yScale.getPixelForValue(0);
    
                var gradientFill = c.ctx.createLinearGradient(0, 0, 0, c.height);
                gradientFill.addColorStop(0, 'green');
                gradientFill.addColorStop(yPos / c.height - 0.01, 'green');
                gradientFill.addColorStop(yPos / c.height + 0.01, 'red');
                gradientFill.addColorStop(1, 'red');
    
                var model = x.data.datasets[0]._meta[Object.keys(dataset._meta)[0]].dataset._model;
                model.backgroundColor = gradientFill;
            }
        }]
    

    And it seems to be working:

    screenshot 2018-10-31 at 14 12 40

    https://jsfiddle.net/x4dvotLn/

Comments are closed.