[Chartjs]-Is there any way to use 2 different color for the same bar in a chart?

1πŸ‘

βœ…

The way I solved it before is by using a stacked bar in chart js. You should go through your values and every time a value is higher then 150 you set 150 in dataset1 and the amount that is above 150 you put in dataset2. and If your amount is lower than 150 you put in the amount in dataset1 and put 0 in dataset2. Here you can see an example of how I did it.

var config = {
  type: 'bar',
  data: {
    labels: ["January", "February", "March", "April", "May"],
    datasets: [{
      type: 'bar',
      label: 'Dataset 1',
      backgroundColor: "blue",
      data: [150, 150, 60, 50, 40],
    }, {
      type: 'bar',
      label: 'Dataset 2',
      backgroundColor: "red",
      data: [45,25,0,0,0]
    }]
  },
  options: {
    scales: {
      xAxes: [{
        stacked: true
      }],
      yAxes: [{
        stacked: true
      }]
    }
  }
};

var ctx = document.getElementById("myChart").getContext("2d");
new Chart(ctx, config);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.0/Chart.bundle.min.js"></script>
<canvas id="myChart"></canvas>

1πŸ‘

Give a try with this code:

const ctx = document.getElementById('chart').getContext('2d');
const data = [150, 150, 60, 50, 40, 152, 300];

new Chart(ctx, {
  type: 'horizontalBar',
  data: {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [{
        fill: 'origin',
      label: "My First dataset",
            borderColor: 'black',
      data: data,
    }]
  },
  options: {
    legend: {
        display: false
    }
  },
   plugins: [{
        beforeRender: function (x, options) {
                var c = x.chart;
            var dataset = x.data.datasets[0];
            var xScale = x.scales['x-axis-0'];
            var xPos = xScale.getPixelForValue(0);
            console.log(c)
            var gradientFill = c.ctx.createLinearGradient(c.width, 0, 133.3333333333335, 0);
            gradientFill.addColorStop(0, 'red');
            gradientFill.addColorStop(xPos / c.height - 0.01, 'red');
            gradientFill.addColorStop(xPos / c.height + 0.01, 'black');
            gradientFill.addColorStop(1, 'black');
            console.log(x.data.datasets[0])
            for (var i = 0; i < x.data.datasets[0]._meta[Object.keys(dataset._meta)[0]].data.length; i++ ) {
              var model = x.data.datasets[0]._meta[Object.keys(dataset._meta)[0]].data[i]._model;
              model.backgroundColor = gradientFill;
            }
        }
    }]
})

Leave a comment