# Change colour of bar in stacked bar chart within range

I'm trying to change the colour of a bar when a number falls within the range. For instance, here is a stacked bar chart

BarChart[{40, 20, 20, 20}, ChartLayout -> "Stacked",
BarOrigin -> Left]


If I have the number 70, I would like to change the colour of the third bar, leaving the other ones the same.

I have tried using ReplaceAll to create a wrapper version as per the first answer of this question. Straightforward way to highlight a single bar in a BarChart Yet, since it doesn't take the sum of my data points, it did not work. Thanks in advance for your help.

Here is one way:

list = {40, 20, 20, 20};
BarChart[
MapAt[
Style[#, Red] &,
list,
FirstPosition[
Accumulate@list,
_?(GreaterThan@70)
]
],
ChartLayout -> "Stacked",
BarOrigin -> Left
]


Essentially, this works by using Accumulate to compute the net bar sizes in the stacked chart. Using FirstPosition, we find the position where the element crossing 70 is. And finally, MapAt allows us to modify the element at the determined position.

An alternative approach is to use a custom ChartElementFunction:

BarChart[list, ChartLayout -> "Stacked", BarOrigin -> Left,
ChartElementFunction -> ({If[#[[1, 1]] <= 70 <= #[[1, 2]], Red],
ChartElementData["Rectangle"][##]} &)]


Or define a function that works for all 4 settings for the option BarOrigin:

ClearAll[ceF]
ceF[t_, color_: Red, cedf_: "Rectangle"] := Module[{tr, part,
bo = ChartingChartStyleInformation["BarOrigin"]},
tr = Switch[bo, Top | Right, -t, _, t];
part = Switch[bo, Top | Bottom | Automatic, 2, _, 1];
{If[#[[part, 1]] <= tr <= #[[part, 2]], ChartingChartStyleInformation["Color"] = color],
ChartElementDataFunction[cedf][##]}] &;


Examples:

list = {40, 20, 20, 20};

Row[Framed @ BarChart[list, ChartLayout -> "Stacked", ImageSize -> 250,
BarOrigin -> #, ChartElementFunction -> ceF[70], PlotLabel -> #] & /@
{Bottom, Top, Left, Right}, Spacer[10]]


Row[Framed @ BarChart[list, ChartLayout -> "Stacked", ImageSize -> 250,
BarOrigin -> #, ColorFunction -> "Rainbow",
ChartElementFunction -> ceF[70, Yellow, "GlassRectangle"], PlotLabel -> #] & /@
{Bottom, Top, Left, Right}, Spacer[10]]