I am currently working on a customized high charts graph where the color of each bar should dynamically change based on the title of an object. In my array graphData
, each object has a title
key.
There are 5 potential titles:
"LOW", "MEDIUM-LOW", "MEDIUM", "MEDIUM-HIGH", and "HIGH"
My goal is to iterate through the array and assign a specific color to each bar corresponding to its title.
Currently, all bars in the graph are assigned the same color based on the last title in the array. I want each bar's color to be determined independently.
For instance, if the last title in the array is "MEDIUM-HIGH," the entire graph turns #DD5F0C
.
Here is a snippet of my code:
Array:
graphData: [
{ title: "LOW", result: 62582 },
{ title: "MEDIUM-LOW", result: 57758 },
{ title: "LOW", result: 8795 },
{ title: "HIGH", result: 262525 },
{ title: "MEDIUM-HIGH", result: 167168 }
]
let graphColor = ""
for (i = 0; i < graphData.length; i++) {
if (graphData[i].title === "LOW") {
graphColor = "#0D6302"
} else if (graphData[i].title === "MEDIUM-LOW") {
graphColor = "#0B7070"
} else if (graphData[i].title === "MEDIUM") {
graphColor = "#DC9603"
} else if (graphData[i].title === "MEDIUM-HIGH") {
graphColor = "#DD5F0C"
} else if (graphData[i].title === "HIGH") {
graphColor = "#C50710"
}
}
HighCharts code :
Highcharts.chart('container', {
chart: {
type: 'bar'
},
title: {
text: "Bar Graph"
},
xAxis: {
},
yAxis: {
min: 0,
formatter: function() {
return this.value + "%";
},
title: {
text: '% of Total'
}
},
legend: {
reversed: false
},
plotOptions: {
series: {
stacking: 'normal'
}
},
series: [{
name: `graphData[0].title`,
color: graphColor,
data: [graphData[0]],
}, {
name: 'graphData[1].title',
color: graphColor,
data: [graphData[1]],
showInLegend: false,
linkedTo: ":previous"
}, {
name: 'graphData[2].title,
color: graphData[0].title,
data: [graphData[2]]
}, {
name: graphData[3].title,
color: '#DC9603',
data: [graphData[3]]
}, {
name: graphData[4].title,
color: graphColor,
data: [graphData[4]]
}, {
name: graphData[5].title,
color: graphColor,
data: [graphData[5]]
}]
});
The expectation is for the color attribute to dynamically change based on the corresponding graphData.title
value at each index.