How-to ensure consistent legend when using PieChart?
DynamicModule[{n = 20},
Column[{Row[{Slider[Dynamic[n], {1, 100, 1}], Dynamic[n]}],
Dynamic[Legended[PieChart[Thread[Style[#[[All, 2]], #[[All, 1]] /.
{True -> Red, False -> Green}] ],
ChartStyle -> {Green, Red}] &@
Tally@RandomChoice[{True, False}, n],
SwatchLegend[{Green, Red}, {False, True}]]]}]]
Alternatively (thanks: Brett Champion):
DynamicModule[{n = 20},
Column[{Row[{Slider[Dynamic[n], {1, 100, 1}], Dynamic[n]}],
Dynamic[PieChart[Thread[Style[#[[All, 2]], #[[All, 1]] /.
{True -> Red, False -> Green}]],
ChartLegends -> SwatchLegend[{Green, Red}, {False, True}]] &@
Tally@RandomChoice[{True, False}, n]]}]]
The Red/Green
problem stems from the fact that Tally
returns tallied values in the order each element is first encountered, and the other issue is because Tally
doesn't return a 0
entry for elements not in the list. Both issues can be solved with a custom tally:
explicitTally[list_,toTally_List] := {#, Count[list, #]} & /@ toTally;
If you use explicitTally[#,{True,False}]
in place of Tally
everything should work correctly. Use is shown below, I also used Transpose
and Apply (@@)
to clean it up a little.
DynamicModule[
{n = 20},
Column[{
Row[{
Slider[Dynamic[n], {1, 100, 1}],
Dynamic[n]
}],
Dynamic[
PieChart[
#2,
ChartLegends -> #1,
ChartStyle -> {Green, Red}
] & @@
Transpose@
explicitTally[RandomChoice[{True, False}, n], {True, False}]
]
}]
]