Carlos Eduardo
Carlos Eduardo

Reputation: 33

How to fill the area between two vertical lines in the chart using chartjs library?

I'm needing to fill the area between two line graphs using chartjs. I found how to do it when you have one line on top of the other, but I want to know when you have two lines side by side and I need the area between them.

For example, the area of ​​a graph like this

For example, the area of ​​a graph like this

The code is this:

    const ctx = document.getElementById('myChart');
    const myChart = new Chart(ctx, {
        type: 'scatter',
        data: {
          datasets: [{
            label: 'linha 1',            
            data:[
              {x: -11, y: 7},
              {x: -11, y: 7},
              {x: -1, y: 8},
            ],
            showLine: true,
            borderColor: '#009999',
            backgroundColor: '#009999',
          }, 
          {
            label: 'linha 2',
            data: [
              {x: 0, y: 7},
              {x: 0, y: 7},
              {x: 8, y: 8},
            ],
            showLine: true,
            borderColor: '#f00',
            backgroundColor: '#f00',
          }
        ]
        },
        options: {
          responsive: false,
        }
    });

Upvotes: 2

Views: 352

Answers (1)

user2057925
user2057925

Reputation: 2653

I think you need a dedicated plugin to do it.

I have created one (it could be improve), see snippet.

const plugin = {
  id: 'myfill',
  beforeDatasetsDraw(chart, args, options) {
    const {ctx, data} = chart;
    ctx.save();
    ctx.fillStyle  = 'rgba(47, 98, 156, 0.2)';
    ctx.beginPath();
    let meta = chart.getDatasetMeta(0);
    let e = meta.data[0];
    ctx.moveTo(e.x, e.y);
    e = meta.data[1];
    ctx.lineTo(e.x, e.y);
    meta = chart.getDatasetMeta(1);
    e = meta.data[1];
    ctx.lineTo(e.x, e.y);
    e = meta.data[0];
    ctx.lineTo(e.x, e.y);
    ctx.fill();
    ctx.restore();
  }
};
const ctx = document.getElementById('myChart');
const myChart = new Chart(ctx, {
   type: 'scatter',
   plugins: [plugin],
   data: {
     datasets: [{
            label: 'linha 1',            
            data:[
              {x: -11, y: 7},
              {x: -1, y: 8},
            ],
            showLine: true,
            borderColor: 'rgb(47, 98, 156)',
          }, 
          {
            label: 'linha 2',
            data: [
              {x: 0, y: 7},
              {x: 8, y: 8},
            ],
            showLine: true,
            borderColor: 'rgb(47, 98, 156)',
          }
        ]
        },
        options: {
          responsive: false,
        }
    });
.myChartDiv {
  max-width: 600px;
  max-height: 400px;
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
<html>
  <body>
    <div class="myChartDiv">
      <canvas id="myChart" width="600" height="400"/>
    </div>
  </body>
</html>

Upvotes: 3

Related Questions