[Chartjs]-Changing the back color of bars in chart js

2๐Ÿ‘

โœ…

A fast solution is to use stacked bars. (like in this official example)

  1. define max Bar maxheight
  2. create a second stacked dataset, that should display as background
  3. to get the right size, for the second dataset, where you just subtract actual value from the maxHeight

Here a demo, how I would do this:

let values = [ 10, 50, 80, 100, 120, 50, 10 ];
let graphMax = 200

let bgColor = '#F8F9FC';
let fgColor1 = '#B0D3FF';
let fgColor2 = '#DACBFF';

const data = {
  labels: [ 1, 2, 3, 4, 5, 6, 7 ],
  datasets: [{
      data: values,
      
      // just add this to alternate colors
      backgroundColor: values.map((v,i) => i % 2 ? fgColor1 : fgColor2),
      barThickness: 30,
      stack: 'Stack 0',
    }, {
      //calculate the difference for the background
      data: values.map( value => graphMax - value),
      backgroundColor: bgColor,
      barThickness: 30,
      stack: 'Stack 0',
    }]
};

const config = {
  type: 'bar',
  data: data,
  options: {
    plugins: {
      // hiding unneeded features
      title:   { display: false },
      legend:  { display: false },
      tooltip: { enabled: false }
    },
    maintainAspectRatio: false,
    interaction: { intersect: false },
    scales: {
      x: { stacked: true },
      y: { stacked: true }
    }
  }
};

new Chart(
    document.getElementById('chart'),
    config
);
<script src="//cdn.jsdelivr.net/npm/chart.js"></script>

<div class="chart" style="height:184px;width:500px">
    <canvas id="chart"></canvas>
</div>

Leave a comment