Usually, when I plot multiple curves in Mathematica
Plot[{x,x^2,x^3},{x,0,1}]
they are given different colors. However, if I try to construct a list inside the Plot[] function,
Plot[Table[x^n, {n, 1, 3}], {x, 0, 1}]
this doesn't work and all the curves come out the same color. The standard advice (e.g. here, here and here), which works but which I don't fully understand, is to wrap the Table[] with an Evaluate[]:
Plot[Evaluate[Table[x^n, {n, 1, 3}]], {x, 0, 1}]
or equivalently
f[x_,n_]:=x^n;
Plot[Evaluate[Table[f[x,n], {n, 1, 3}]], {x, 0, 1}]
This work in this case, because f[x_]:=x^n is a simple function. However, suppose I have a complicated function g[y] which uses its argument y as a bound for an iterator:
g[y_] := Total[Table[1, {z, 1, Round[y + 1]}]]
Mathematica is not smart enough to recognize that this is equivalent to g[y_]:=Round[y]+1, and usually such a simplification will not be possible anyways. g[y] cannot be evaluated symbolically, because of the iterator, although it's still plenty fast when given a machine number. Then trying to plot various curves using a table constructed with g[y] without Evaluate[]
Plot[Table[g[x*n], {n, 1, 3}], {x, 0, 1}]
will make all the curves the same color. Adding Evaluate[]
Plot[Evaluate[Table[g[x*n], {n, 1, 3}]], {x, 0, 1}]
causes Mathematica to throw an error message about using a bad iterator. (Table::iterb: "Iterator {z,1,Round[1+x]} does not have appropriate bounds).
Why, exactly, is Evaluate[] necessary in the simple case? Is it true that Plot[] is interpreting the table as a multi-valued function? Why?
How can we achieve the same result in the complicated case where the technique fails?







g[y]. Ideally we wouldn't need to do this because g might be a black box. We could just defineh[y_]:=Hold[g[y]]and use that, although this is still slightly awkward. – Jess Riedel Jul 23 '12 at 20:47Plotwould work with expressions insideHold! Where is this documented? – Mr.Wizard Jul 24 '12 at 10:06Plotmust be usingReleaseHoldat some point in the evaluation. And not all the plotting functions behave the same way:DiscretePlot[Evaluate@Table[g[n*x], {n, 1, 3}], {x, 0, 1, 0.1}]produces empty axes, for example. Just when you think you understand something... – DGrady Jul 24 '12 at 18:28