Skip to content Skip to sidebar Skip to footer

Chartjs Gradient Background Color Based On Min And Max Values

I'm using chartjs with vue-chart to display some data in my application and actually what I would like to achieve is to have a Bar chart with a background color from red to green.

Solution 1:

The Plugin Core API offers a range of hooks that may be used for performing custom code. You can use the afterLayout hook for creating a gradient for the y-axis that spreads that desired area (values 0 to 5).

let yAxis = chart.scales["y-axis-0"];
let yBottom = yAxis.getPixelForValue(0);
let yTop = yAxis.getPixelForValue(5);          
let gradient = ctx.createLinearGradient(0, yBottom, 0, yTop);  

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

const data = [2, 2.25, 3.3];

newChart(document.getElementById("chart"), {
  type: "bar",
  plugins: [{
    afterLayout: chart => {
      let ctx = chart.chart.ctx;
      ctx.save();
      let yAxis = chart.scales["y-axis-0"];
      let yBottom = yAxis.getPixelForValue(0);
      let yTop = yAxis.getPixelForValue(5);          
      let gradient = ctx.createLinearGradient(0, yBottom, 0, yTop);   
      gradient.addColorStop(0, '#FF5722');           
      gradient.addColorStop(0.5, '#FFC107'); 
      gradient.addColorStop(1, '#8BC34A');           
      chart.data.datasets[0].backgroundColor = gradient;
      ctx.restore();
    }
  }],
  data: {
    labels: ["A", "B", "C"],
    datasets: [{
      label: "Evaluation",
      data: data
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          min: Math.min(...data) - 0.2,
          max: Math.max(...data) + 0.2,
          stepSize: 0.5
        }
      }]
    }
  }
});
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script><canvasid="chart"height="80"></canvas>

Post a Comment for "Chartjs Gradient Background Color Based On Min And Max Values"