0

I am trying to reproduce this image below in Chart.js.

My question is how do I fill the area based on the line values as in the image? At the moment the data is correctly displayed, but the coloring is not managed.

Here is the code I have at the moment:

var xPoints = [];
var yPoints = [];
var storage = [];
for(var i=0; i<data.cost.length; i++)
        { 
            xPoints[i] = data.electricity[i];
            yPoints[i] = data.cost[i];
            x = xPoints[i];
            y = yPoints[i];
            var coordinates = {x: x, y: y};
            storage.push(coordinates); 
        }
var ctx = document.getElementById("myChart");
var chart_wrapper = document.getElementsByClassName("chart-wrapper");

 var myChart = new Chart(ctx, {
          type: "scatter",
          data: {
            
            datasets: [
              {
                label: label,
                data: storage,
                yAxisID: "primary",
                borderWidth: 4,
                type: "line",
                backgroundColor: "rgba(107, 80, 255)",
              },
              
            ],
          },
          options: options }});

Thank you enter image description here

AndrewDAG
  • 65
  • 1
  • 2
  • 12
  • Does one of these answer your question? https://stackoverflow.com/a/61695757/2358409 / https://stackoverflow.com/a/63101243/2358409 – uminder Aug 12 '20 at 04:04
  • The answer here https://stackoverflow.com/questions/61691543/chartjs-how-can-i-get-different-color-fills-between-my-two-datasets-in-a-line-g/61695757#61695757 seems to address partially my problem. In fact, it doesn't consider the x-axis. When I apply the code my chart gets literally "cut in half" and can't visualize properly the object. – AndrewDAG Aug 12 '20 at 08:42

1 Answers1

0

Answer:

this solved my problem.

plugins: [{
            beforeRender: function (x, options) {
                var c = x.chart
                var dataset = x.data.datasets[0];
                var yScale = x.scales['primary'];
                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;
            }
        }],
AndrewDAG
  • 65
  • 1
  • 2
  • 12