Skip to main content

charts - How to create a stacked BarChart with custom bar origins as function?


I want to create a simple stacked bar chart where the bars start a custom y-axis point and end at another y-axis point.


So far I have:


BarChart[{{2, 4}, {-2, 6}}, ChartLayout -> "Stacked"]

which gives:



Stacked bar chart


However, I want a single bar on the left that originates at 2 and goes up to 4, and on the right a bar that starts at -2 and goes up to 6.


How can I achieve this? I also experimented around with the ChartElementFunction but I can not find how to specify a starting point of the bar.


Thanks for any help in advance.



Answer



I'm not sure whether this is documented or not. You can pass additional arguments to the ChartElementFunction like this:


r[{{xmin_, xmax_}, {ymin_, ymax_}}, y_, {origin_}] :=
Rectangle[{xmin, ymin + origin}, {xmax, ymax + origin}]

BarChart[{{1} -> 1, {1} -> 2, {2} -> 3}, ChartElementFunction -> r]


Mathematica graphics


edit


Perhaps more elegant and somewhat more obscure:


r[a_, _, {origin_}] := Rectangle @@ Transpose[a + {0, origin}]

Comments