I'm new to JavaScript and i'm using chart.js to create some data visualizations, and i need to change the color of the entire bar for different values, the code i have so far is what follows, but i can't make it work, this isn't giving me any errors, so i don't know were to go.
var dData1 = 90; ///////CARREGAR DADOS DE FACTURAÇÃO (for developer)
var dData2 = 70; ///////CARREGAR DADOS DE FACTURAÇÃO (for developer)
var barChartData = {
labels: ["MÊS", "ANO"],
datasets: [{
fillColor: "#f37c8a",
strokeColor: "none",
data: [dData1, dData2]
}]
}
if (dData1 < 75)
{
barChartData.datasets[0].fillColor = "#f37c8a";
}
else if (dData1 > 76 && dData1 < 85)
{
barChartData.datasets[0].fillColor = "#f3e97c";
}
else if (dData1 > 86)
{
barChartData.datasets[0].fillColor = "#9ae27d";
} else
{
barChartData.datasets[0].fillColor = "#fff";
};
if (dData2 < 75)
{
barChartData.datasets[0].fillColor = "#f37c8a";
}
else if (dData2 > 76 && dData1 < 85)
{
barChartData.datasets[0].fillColor = "#f3e97c";
}
else if (dData2 > 86)
{
barChartData.datasets[0].fillColor = "#9ae27d";
} else
{
barChartData.datasets[0].fillColor = "#fff";
};
You need to set the colors for the
bars
after generating the chart. You'll need to set thefillColor
, thehighlightFill
and_saved.fillColor
(which Chart.js uses to restore the bar color after a tooltip hover)So you need something like
for the 1st block, where
barChart
is your chart object. Note that the above code assumes a single series of 2 elements.Fiddle - https://jsfiddle.net/2a86gqsa/
Note that you had
dData1 < 85
in the second block - I changed it todData2 < 85
. Seeing that much of the code for the 2 blocks are common you might want to move it to a function.Solved, i was calling the items inside the library wrong.