[Chartjs]-Changing line color below specific value in Chart.js

2👍

The solution provided by this answer can easily be adapted to also work with Chart.js v3.7.1.

Please take a look at below runnable code and see how it works.

const threshold = 25;

new Chart('myChart', {
  type: 'line',
  plugins: [{
    afterLayout: chart => {
      let ctx = chart.ctx;
      ctx.save();
      let yAxis = chart.scales.y;
      let yThreshold = yAxis.getPixelForValue(threshold);
      let gradient = ctx.createLinearGradient(0, yAxis.top, 0, yAxis.bottom);
      gradient.addColorStop(0, 'green');
      let offset = 1 / yAxis.bottom * yThreshold;
      gradient.addColorStop(offset, 'green');
      gradient.addColorStop(offset, 'red');
      gradient.addColorStop(1, 'red');
      chart.data.datasets[0].borderColor = gradient;
      ctx.restore();
    }
  }],
  data: {
    labels: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
    datasets: [{
      label: 'My Dataset',
      data: [32, 44, 29, 33, 18, 15, 30],
      fill: false,
      lineTension: 0.2
    }]
  },
  options: {
    plugins: {
      legend: {
        display: false
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
<canvas id="myChart" height="80"></canvas>

1👍

I have made a detailed response here that can help you.

Here is the code:

var myLineChart = new Chart(ctx, {
  type: 'line',
  plugins: [{
    afterLayout: chart => {
      let ctx = chart.chart.ctx;
      ctx.save();
      let yAxis = chart.scales["y-axis-0"];
      let yThresholdMax = yAxis.getPixelForValue(data.limits.max);  
      let yThresholdMin = yAxis.getPixelForValue(data.limits.min);  

      let offsetMax = 1 / yAxis.bottom * yThresholdMax; 
      let offsetMin= 1 / yAxis.bottom * yThresholdMin; 

      let gradient = ctx.createLinearGradient(0, yAxis.top, 0, yAxis.bottom);   
      
      gradient.addColorStop(0, 'red'); 
      gradient.addColorStop(offsetMax, 'darkred'); 
      gradient.addColorStop(offsetMax, 'blue'); 
      gradient.addColorStop(offsetMin, 'blue');
      gradient.addColorStop(offsetMin,'darkred');
      gradient.addColorStop(1,"red");           
      chart.data.datasets[0].borderColor = gradient;    
      ctx.restore();
    }
  }],
  // The data for our dataset
  data: {
      ......
  },
    options: {
    ........
   }
});

Leave a comment