1
$\begingroup$

I want to be able to use Manipulate on Show[plot1,plot2] in order to make groups of plot appear/disappear. I've tried running the code below but the checkmarks doesn't add/remove the visibility of plots.

plot1 = Plot[{Cos[x], 2*Cos[x], 1/2*Cos[x]}, {x, 0, 5}, 
   PlotLegends -> LineLegend["Expressions"], PlotStyle -> Orange];
plot2 = Plot[{Sin[x], 2*Sin[x], 1/2*Sin[x]}, {x, 0, 5}, 
   PlotLegends -> LineLegend["Expressions"], PlotStyle -> Green];
Manipulate[
 Show[plot1, plot2, 
  PlotStyle -> {Opacity[a], Opacity[b]}], {{a, 1, "Cosines"}, {1, 
   0}}, {{b, 1, "Sines"}, {1, 0}}, ControlPlacement -> Top, 
 FrameMargins -> 0]

The following produces the combined plot of: Show Manipulate

$\endgroup$
1

2 Answers 2

3
$\begingroup$

Try

Manipulate[
 Module[{plot1, plot2, x},
  plot1 = 
   Plot[{Cos[x], 2*Cos[x], 1/2*Cos[x]}, {x, 0, 5}, 
    PlotLegends -> LineLegend["Expressions"], 
    PlotStyle -> Directive[{Orange, Opacity[a]}]]; 
  plot2 = Plot[{Sin[x], 2*Sin[x], 1/2*Sin[x]}, {x, 0, 5}, 
    PlotLegends -> LineLegend["Expressions"], 
    PlotStyle -> Directive[{Green, Opacity[b]}]];
  Show[plot1, plot2]
  ],
 {{a, 1, "Cosines"}, {1, 0}},
 {{b, 1, "Sines"}, {1, 0}},
 ControlPlacement -> Top, FrameMargins -> 0,
 TrackedSymbols :> {a, b}
 ]

enter image description here

$\endgroup$
2
  • $\begingroup$ Produces the correct result, but in principle using Opacity if just hiding/displaying things is needed is not the preferred way. $\endgroup$
    – Mathias
    Feb 9, 2022 at 16:23
  • $\begingroup$ @Mathias I agree. But this is not my method. I just fixed the issue with the OP code to make it work. $\endgroup$
    – Nasser
    Feb 9, 2022 at 22:42
2
$\begingroup$

Instead of changing the plots opacity I would rather recommend to exclude/include them in the Show command. Here is a working solution:

First generate the plots

plot1 = Plot[{Cos[x], 2*Cos[x], 1/2*Cos[x]}, {x, 0, 5}, PlotLegends -> "Expressions", PlotStyle -> Dashed];
plot2 = Plot[{Sin[x], 2*Sin[x], 1/2*Sin[x]}, {x, 0, 5}, PlotLegends -> "Expressions", PlotStyle -> Thick];

And then use simple If to decide if the plot should be shown.

Manipulate[
 Show[{If[a == 1, plot1, Nothing], If[b == 1, plot2, Nothing]}],
 {{a, 1, "Cosines"}, {1, 0}},
 {{b, 1, "Sines"}, {1, 0}},
 ControlPlacement -> Top,
 FrameMargins -> 0,
 TrackedSymbols :> {a, b}
]

In this case also the PlotLegend is displayed or hidden for the choosen plots.enter image description here

$\endgroup$

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.