Message Boards Message Boards

0
|
2294 Views
|
4 Replies
|
2 Total Likes
View groups...
Share
Share this post:

Trouble with syntax combining Plot and Switch

Posted 1 year ago

Hi! If I

Plot[{Sin[x],Cos[x]},{x,0,2π}]

then I get the sine plotted in the default blue, and the cosine in the default orange. The command

key="one";
Switch[key,"one",{Sin[x],Cos[x]},"two",{-Sin[x],-Cos[x]}]

gives {Sin[x],Cos[x]}. Following this up with

Plot[%,{x,0,2π}]

results again in both curves being plotted in different colors. However

Plot[Switch[key,"one",{Sin[x],Cos[x]},"two",{-Sin[x],-Cos[x]}],{x,0,2π}]

results in both curves being plotted in the same color, and I could not manage to manually change that by using the option PlotStyle option.

Why is that so, and how can I change the plot colors if I use Plot with Switch in this way?

An example notebook is attached!
Thanks for help! : )

POSTED BY: Gernot H
4 Replies
Posted 1 year ago

Plot needs to hold its arguments. The first argument is an expression that needs to be evaluated for each sample point. If it were evaluated immediately, it might no longer be in a form suitable for substituting the sample points. Now, I don't know why, but it seems like Plot commits to the color scheme based on the number of plot expressions it initially sees. So, if you pass in a list, it seems like it'll count the number of items in the list and use that number to determine how many different colors to use. In your case, you've passed in a single expression (the Switch--remember, it's being held, so Plot has no idea that it will eventually evaluate to a list), so Plot (apparently--I'm really just guessing here) commits to a single color.

The most common workaround for situations like these is to wrap the expression you want to plot in Evaluate:

Plot[Evaluate[
  Switch[key, "one", {Sin[x], Cos[x]}, "two", {-Sin[x], -Cos[x]}]], {x, 0, 2 \[Pi]}]

But you need to be careful with this strategy and ensure that after a forced evaluation the expression will still be in a form that Plot can use.

POSTED BY: Eric Rimbey
Posted 1 year ago

I think your guess might be right here! : ) In any case, the solution works. Thanks a lot!

POSTED BY: Gernot H
Posted 1 year ago

It works if Evaluate is used to, well, evaluate the Switch argument before assigning values to x.

key="one";
Plot[Evaluate@Switch[key,"one",{Sin[x],Cos[x]},"two",{-Sin[x],-Cos[x]}],{x,0,2*Pi}]
POSTED BY: Hans Milton
Posted 1 year ago

Thank you so much!

POSTED BY: Gernot H
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract