1
$\begingroup$

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?

enter image description here

enter image description here

$\endgroup$
2
  • $\begingroup$ fs order/content is affected by your actions while PlotStyle setting stays the same and independent of those actions. $\endgroup$
    – Kuba
    Commented Nov 8, 2017 at 14:44
  • $\begingroup$ Any idea on how to fix this directly? $\endgroup$
    – Manfredo
    Commented Nov 9, 2017 at 10:09

1 Answer 1

2
$\begingroup$

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.

$\endgroup$
1
  • $\begingroup$ 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 $\endgroup$
    – Manfredo
    Commented Nov 9, 2017 at 10:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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