Chartjs-I want to put bar of different color by the values in chart.js

1👍

You can use scriptable options for this:

const options = {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 20, 23, 50, 60, 65],
      backgroundColor: (ctx) => {
        if (ctx.raw <= 20) {
          return 'red';
        }

        if (ctx.raw <= 60) {
          return 'yellow';
        }

        return 'green';
      }
    }]
  },
  options: {}
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.2/chart.js"></script>
</body>

Leave a comment