[Chartjs]-I want to change color of individual bar of bar graph

1👍

From what I could figure out is that your question is mostly related to the usage of chart.js. My solution to your problem would look like the following:

//Load your data (obviously this is a hardcoded example, you could use any backend code like PHP):
let data = [12, 19, 74, 38, 45, 62];
//Insantiate fields you would like to use, such as `colors` for background color and `borderColors` for, you guessed it, the color of the borders:
let colors = [];
let borderColors = [];
//Set the field values based on value (this would be your logic):
$.each(data, function(index, value) {
  //When the value is higher than 45, set it to given color, else make them the other color (in the example the bars would appear red-ish):
  if(value > 45) {
    colors[index] = "rgba(0, 255, 0, 0.2)";
    borderColors[index] = "rgba(0, 255, 1)";
  }
  else {
    colors[index] = "rgba(249, 4, 17, 0.2)";
    borderColors[index] = "rgba(249, 4, 17, 1)";
  }
});

//Any code related to creating the chart with the bars (you could find any documentation regarding this code on the homepage of Chart.js):
let ctx = document.getElementById('myChart');
let myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['1', '2', '3', '4', '5', '6'],
        datasets: [{
            label: 'Records from mysql',
            //Populate your fields here:
            data: data,
            backgroundColor: colors,
            borderColor: borderColors,
            hoverBackgroundColor: 'rgba(30, 0, 200)',
            hoverBorderColor: 'rgba(200, 200, 197)',
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }]
        }
    }
});
#chart-container {
  width: 640px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>
<div id="chart-container">
  <canvas id="myChart"></canvas>
</div>

JSFiddle

I applied some code I found on the following post on Github:

$.each(data, function(index, value) {
  //When the value is higher than 45, set it to given color, else make them the other color (in the example the bars would appear red-ish):
  if(value > 45) {
    colors[index] = "rgba(0, 255, 0, 0.2)";
    borderColors[index] = "rgba(0, 255, 1)";
  }
  else {
    colors[index] = "rgba(249, 4, 17, 0.2)";
    borderColors[index] = "rgba(249, 4, 17, 1)";
  }
});

If anyone knows a more clean solution, please let me know in the comments.

Leave a comment