# How do I use If to plot a function conditionally

I am trying to use the If so that when the 1st argument is true, it plots a graph of a function and when false, returns 0. I know that the format of an if statement is If[x, TRUE, FALSE], but I don't know how the input works when I want to check the function for x within the If expression so that I can graph that function when it is true.

New contributor
Bob is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

This should show you how to do it.

Manipulate[
If[x, Plot[Sin[2 π t], {t, 0, 1}], 0],
{x, {True, False}, Setter}]


Or, perhaps, this will be closer to the answer you are looking for:

With[{x = True}, If[x, Print[Plot[Sin[2 π t], {t, 0, 1}]], 0]]


The above will will show your plot, and this will return zero.

With[{x = False}, If[x, Print[Plot[Sin[2 π t], {t, 0, 1}]], 0]]


In a notebook it looks like this:

Plot works with logical statements, for instance

Plot[If[x>0,x^2,0],{x,-10,10}]


Also see Piecewise or Switch instead of nesting Ifs for multiply defined functions.

• When I try to test the input, it results in an output of the graph even if x is false for some reason. – Bob yesterday
• Plot f1(x) between x = -10 and x = +10, where f1(x) = +x2 when x is positive, f1(x) = -50 when x is -2 or smaller, and f1(x) = 0 otherwise – Bob yesterday