# TogglerBar and Legend color mismatch

I have this piece of code

XuColor = {Red, Green, Blue};
XuNames = {"cat", "dog", "rat"};

fun2 = Thread[{Sin[x], Cos[x], Tanh[x]} -> XuNames];
Manipulate[
Legended[Plot[fs, {x, 0, 3 Pi}, PlotStyle -> XuColor],
Placed[LineLegend[XuColor, XuNames, LegendLayout -> "Row"],
Below]], {fs, fun2, ControlType -> TogglerBar}]


However the Legend is displaying the wrong colours (rat should be the tanh function in blue etc.) The colour of the curve actually depends on the order with which I click the toggler. If I have only the rat curve then it is displayed with the correct color (second image) How do I fix this?

• fs order/content is affected by your actions while PlotStyle setting stays the same and independent of those actions.
– Kuba
Nov 8 '17 at 14:44
• Any idea on how to fix this directly? Nov 9 '17 at 10:09

You can use an Association to do this as follows:

fun2 = <|"cat" -> {"color" -> Red, "f" -> Sin[x]},
"dog" -> {"color" -> Green, "f" -> Cos[x]},
"rat" -> {"color" -> Blue, "f" -> Tanh[x]}|>;

Manipulate[
Legended[
Plot[Evaluate["f" /. (fs /. fun2)],
{x, 0, 3 Pi}
, PlotStyle -> ("color" /. (fs /. fun2))
],
Placed[LineLegend["color" /. (Keys@fun2 /. fun2), Keys@fun2, LegendLayout -> "Row"], Below]]
, {fs, Keys@fun2, ControlType -> TogglerBar}]


Which will 'automatically' keep the ordering correct.

If you prefer to keep the same structures you'll have to make a slight modification

XuColor = {Red, Green, Blue};
XuNames = {"cat", "dog", "rat"};

fun2 = Thread[{Sin[x], Cos[x], Tanh[x]} -> XuNames];
Manipulate[
Legended[
Plot[
Evaluate@Keys@fun2[[fs]],
{x, 0, 3 Pi},
PlotStyle -> XuColor[[fs]]
],
Placed[LineLegend[XuColor, XuNames, LegendLayout -> "Row"], Below]
],
{
{fs, 1},
Table[i -> XuNames[[i]], {i, Length@XuNames}],
ControlType -> TogglerBar
}
]


This way fs chooses an integer but uses your labels, and you takes the appropriate part of each list where needed. Unless fun2 needs to be in the form it's in, I'd suggest just making it a list of the functions without the mapping to names. Then you can drop the Keys function.

• Thanks, I was hoping to keep the structure of the code more similar to the one I have, because this is only a reproducible example part of a larger notebook. But your solution works Nov 9 '17 at 10:10