Good day, first of all I thank anyone who can help me, I'm new to this and I'm creating a chart with chart.js I need each bar to change color according to different conditionals, for example for a it must be green if the value is found between 0 -15, orange between 16 and 30. while for b green 0 - 10, orange from 11-20, I hope you can help me.
var chartColors = {
color1: 'rgba(132, 228, 57, 0.7)',
color2: 'rgba(197, 228, 51, 0.9)',
color3: 'rgba(251, 251, 0, 0.9)',
color4: 'rgba(218, 117, 57, 0.5)',
color5: 'rgba(218, 57, 57, 0.5)'
};
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Categorías"],
datasets: [{
label: 'a',
backgroundColor: [
chartColors.color1,
chartColors.color1,
chartColors.color1,
chartColors.color1,
chartColors.color1
],
data: [29]
},{
label: "b",
data: [31],
backgroundColor: [
chartColors.color1
],
},{
label: "c",
data: [41],
backgroundColor: [
chartColors.color1
],
},{
label: "d",
data: [30],
backgroundColor: [
chartColors.color1
],
},{
label: "e",
data: [61],
backgroundColor: [
chartColors.color1
],
}
],
}
});
var colorChangeValue = 50; //set this to whatever is the deciding color change value
var dataset = myChart.data.datasets[0];
for (var i = 0; i < dataset.data.length; i++) {
if (dataset.data[i] < 30) {
dataset.backgroundColor[i] = chartColors.color1;
}
else if ((dataset.data[i] > 31) && (dataset.data[i] <= 39)){
dataset.backgroundColor[i] = chartColors.color2;
}
else if ((dataset.data[i] > 40) && (dataset.data[i] <= 50)){
dataset.backgroundColor[i] = chartColors.color3;
}
else if ((dataset.data[i] > 51) && (dataset.data[i] <= 60)){
dataset.backgroundColor[i] = chartColors.color4;
}
else{
dataset.backgroundColor[i] = chartColors.color5;
}
}
myChart.update();
I do not know if it is the correct way since I do not know how to create or isolate each bar to apply the required conditional to each of these.
You are accessing the wrong dataset. You need to access
myChart.data.datasets
like this:would be something like this...
a validation is simply made with the ranges, and with this you can verify what color it will have