[Chartjs]-Chart.js: Bar chart multiple colors

2👍

New answer:

My original answer bothered me and I thought there must be a better way to achieve this style. So here’s a much better solution that uses a radial gradient.

Note that this implementation is quite naïve in that it only supports a single dataset!

const colours = [
  { primary: '#fec1c6', shadow: '#e8b0b5' },
  { primary: '#bdeeed', shadow: '#aad2d0' },
  { primary: '#e4da84', shadow: '#d3ca76' }
];

new Chart(document.getElementById('chart'), {
  type: 'doughnut',
  data: {
    datasets: [{
      data: [3, 2, 2]
    }]
  },
  options: {
    cutoutPercentage: 65
  },
  plugins: [{
    beforeDatasetsUpdate: c => {
      const x = (c.chartArea.right + c.chartArea.left) / 2,
        y = (c.chartArea.bottom + c.chartArea.top) / 2,
        bgc = [];

      for (let i = 0; i < colours.length; i++) {
        const gradient = c.ctx.createRadialGradient(x, y, c.innerRadius, x, y, c.outerRadius);

        gradient.addColorStop(0, colours[i].shadow);
        gradient.addColorStop(.4, colours[i].shadow);
        gradient.addColorStop(.45, colours[i].primary);
        gradient.addColorStop(1, colours[i].primary);

        bgc.push(gradient);
      }
      c.config.data.datasets[0].backgroundColor = bgc;
    }
  }]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chart" height="75"></canvas>

Original answer:

If you don’t mind a ‘dirty’ solution you can achieve a similar visual result by duplicating your dataset, e.g.:

const values = [3, 2, 2],
  primaryColours = ['#fec1c6', '#bdeeed', '#e4da84'],
  secondaryColours = ['#e8b0b5', '#aad2d0', '#d3ca76'];

new Chart(document.getElementById('chart'), {
  type: 'doughnut',
  data: {
    datasets: [{
      data: values,
      weight: 2,
      backgroundColor: primaryColours,
      borderColor: primaryColours
    }, {
      data: values,
      weight: 1,
      backgroundColor: secondaryColours,
      borderColor: secondaryColours
    }]
  },
  options: {
    cutoutPercentage: 65
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chart" height="75"></canvas>

Leave a comment