2
$\begingroup$

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]

enter image description here

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.

$\endgroup$
4
$\begingroup$

Here is one way:

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

enter image description here

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.

| improve this answer | |
$\endgroup$
2
$\begingroup$

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"][##]} &)]

enter image description here

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 = Charting`ChartStyleInformation["BarOrigin"]},
   tr = Switch[bo, Top | Right, -t, _, t];
   part = Switch[bo, Top | Bottom | Automatic, 2, _, 1];
   {If[#[[part, 1]] <= tr <= #[[part, 2]], Charting`ChartStyleInformation["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]]

enter image description here

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

enter image description here

| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.