Mathematica: Can I match the BarChart legend with stacks?

I would like the vertical arrangement of colors in stacked bars to match the arrangement of colors in the chart legend. But no matter what I try, they do not match. Here is the situation

BarChart[{{5, 37, 56}, {22, 49, 28}, {31, 60, 10}}, ChartLayout -> "Percentile", ChartLegends -> Placed[{"1-Volume", "2-Area", "3-Length"}, Right], ChartLabels -> {{"Before", "During", "After"}, None}] 

Chart1

In the real example, the legend has a few more entries (6), so it would be nice if the order of the colors of the legend corresponded to the order in bars. I understand that I could set ChartLegends to display in Bottom , but it doesn’t look good, given the many legend entries.

In addition, changing the Legends list does not work as desired. The text of the legends was reordered, but the colors were not reordered (see below), so the legend labels no longer correspond to the data on the diagram.

Reordering data (or data and legend elements) also does not work.

Any suggestions?

enter image description here

+6
source share
3 answers
 BarChart[{{5, 37, 56}, {22, 49, 28}, {31, 60, 10}}, ChartLayout -> "Percentile", ChartLegends -> {"1-Volume", "2-Area", "3-Length"}, ChartLabels -> {{"Before", "During", "After"}, None}] /. Column[List[a : Grid[List[___]] ..]] :> Column[ Reverse@List @a] 

enter image description here

Edit

Remember to use FullForm if you want to ruin the internal structure of Graphics / Chart / Plot

+10
source

Based on a nice answer from Belisarius , an alternative method using Part

 bc[[2,1,1,1]]= Reverse@bc [[2,1,1,1]];bc 

This can be done from FullForm and

 Position[bc, #, Infinity]& /@ {Framed[___], Column[___],List[___,"1-Volume",___]} 

or any of these, possibly trial and error.

Although this is not a question, the Simon trick (see here ) can be used to further control the legend.

 bc/.Labeled[g_,Framed[leg_],pos_]:> Labeled[g,Framed[leg,FrameStyle->Orange,RoundingRadius->10, Background->LightYellow],pos] 

for example, gives the following:

enter image description here

Part can also be used to remove the border around the legend (see this question), but the Simon method is much more universal.

 bc[[2]]=bc[[2,1]];bc 
+6
source

You can use LegendContainer for this.

 SetOptions[Legending`GridLegend, Legending`LegendContainer -> ( Framed@MapAt [Reverse, #, {1, 1}] &)]; BarChart[{{5, 37, 56}, {22, 49, 28}, {31, 60, 10}}, ChartLayout -> "Percentile", ChartLegends -> {"1-Volume", "2-Area", "3-Length"}, ChartLabels -> {{"Before", "During", "After"}, None}] 

same as belisarius' graph

+2
source

All Articles