# How to plot a function depending on a condition?

I'm plotting several functions at once:

rotationAngle = 0;
x01 = 100;
y01 = 200;

Plot[
{
Tan[rotationAngle] x - Tan[rotationAngle] x01 + y01,
Tan[rotationAngle + Pi/2] x - Tan[rotationAngle + Pi/2] x01 + y01
},
{x, -100, 100}
];


The problem is, that when rotationAngle has a value, which implicates the Tan[Pi/2] expression, I get a warning Indeterminate expression 200+ComplexInfinity+ComplexInfinity encountered and nothing is plotted.

I understand that the problem is with the expression Tan[Pi/2] which is undefined, so is there a way to circumvent this?

I tried to use ConditionalExpression:

Plot[
{
ConditionalExpression[
Tan[rotationAngle + Pi/2] x - Tan[rotationAngle + Pi/2] x01 + y01,
rotationAngle != 0
]
},
{x, -100, 100}
];


but that hasn't helped, the warning is still there.

The If statement cannot be inserted inside the Plot one, I tried this either.

So the question is: Is there a way to plot a function only when a condition is true, and otherwise omit it, while plotting every other function?

• Do you want an empty plot or no plot? Commented Oct 18, 2017 at 16:24
• @JohnDoty, I want no graph for exactly that function, because I'm plotting other functions in the same Plot call, and they must be visible
– d.k
Commented Oct 18, 2017 at 16:25

If[rotationAngle != 0,
Plot[Tan[rotationAngle + Pi/2]*x - Tan[rotationAngle + Pi/2]*x01 +
y01, {x, -100, 100}]
]


Edit:

To handle problems with single functions in multifunction plots, you could instead do something like this:

f = Function[{theta, offset},
If[OddQ[(theta + offset)*2/Pi],
Nothing,
Function[x, Tan[theta + offset]*x - Tan[theta + offset]*x01 + y01]
]]

Plot[Evaluate@{f[rotationAngle, 0][x],
f[rotationAngle, Pi/2][x]}, {x, -100, 100}]

• Is this the only way? I would like to avoid it, because it will induce a considerable amount of copy/paste code
– d.k
Commented Oct 18, 2017 at 16:37
• Why copy/paste? Commented Oct 18, 2017 at 16:49
• @JohnDoty because, I'm plotting several functions in one Plot call. So I would need to write If … Plot [func1, func2_variant1], Plot[func1, func2_var2] and so on
– d.k
Commented Oct 18, 2017 at 16:51
• where func1 will be an exact copy of another func1 etc.
– d.k
Commented Oct 18, 2017 at 16:52
• actually, I decided to comment out the erroneous functions by hand with (* *), but the answer, that there is no simpler way is by itself pretty satisfactory
– d.k
Commented Oct 18, 2017 at 19:33

Remember that Mathematica is fundamentally an expression rewriting system. Get it to rewrite your code, don't cut and paste.

First, define a function that makes one plot, and yields Nothing if the plot cannot be made:

pl[angle_, x01_, y01_] :=
Plot[Tan[angle] x - Tan[angle] x01 + y01, {x, -100, 100}] /;
Mod[angle, Pi] != Pi/2
pl[angle_, x01_, y01_] := Nothing


Then, construct a list of plots and Show them together. Nothing is automagically removed:

Show[Table[pl[a, 100, 200], {a, 0, Pi/2, Pi/2}]]