FAQ - Error when plotting

When I tried to plot something I got a message something like this?

What did I do wrong?  What I'm plotting should be a real valued function or a list of them.

The Short Answer (maybe)

Your problem could be because of the way Plot is defined with an attribute called HoldAll.

Attributes[Plot]

The short answer to possibly fixing this problem is to wrap the first argument —what you're plotting – inside the function Evaluate.  So if this is what you get the error message from:

Plot[something, {x, a, b}]

then the following might solve your problem

Plot[Evaluate[something], {x, a, b}]

The Long Answer

If Plot is given a function in its first argument that produces anything be a real number, then you will get an error like the one that is the subject of this question.  For example, it should be obvious why you get a problem here.

Plot[Sqrt[x], {x, -1, 1}]

Here is another example where the error is clear and can't be fixed with Evaluate.  We assume y hasn't been defined, so we clear it here.

Clear[y];
Plot[ x + y, {x, 0, 1}]

However, here is one that we would expect to work.   First we define y as a function of x with an explicit parameter, b.

y[b_] :=  Sin[b x ]

We can generate a list of expressions in terms of x this way:

Map[y, {1, 2, 3}]

Generally it is possible to plot lists of functions, so we might try the following, but it generates the same error as above.

Plot[Map[y, {1, 2, 3}], {x, 0, Pi}]

The problem is that, for a good reason, the expression Map[y, {1, 2, 3}] isn't evaluated right away, so when Mathematica tries to substitute a real number for x, it isn't substituted into {sin(x), sin(2 x), sin(3 x)}.   However explicitly telling Mathematica to evaluate the Map expression gives us the desired result.

Plot[Evaluate[Map[y, {1, 2, 3}]], {x, 0, Pi}]

Why make things to difficult?  The reason is that an opposite problem will frequently occur if the first argument isn't held.   For example, the following Plot should work as expected, even though we happen to have assigned a value for w.

w = 0.1;
Plot[E^w, {w, -1, 1}]

If the first argument of Plot is evaluated we get

w = 0.1;
Plot[Evaluate[E^w], {w, -1, 1}]

So, without the HoldAll attribute, we would have to carefully choose symbols with no value before plotting, which would be just one of the problems that would appear.