I can get a plot to generate legends for different functions when these functions are put into a hand-coded list. However, when I generate the list of functions using Table[] only one legend is generated. In the code below four plots are generated but only the first two have different legends and colors for the two curves plotted.

Is there a way to produce one legend per curve plotted when the list of functions is generated by Table (or some other function)?

f1[x_] := Sin[x];
f2[x_] := Cos[x];
f = {f1, f2}
Plot[{f1[x], f2[x]}, {x, 0, 2 Pi}, PlotLegends -> {"Sin", "Cos"}]
Plot[{f[[1]][x], f[[2]][x]}, {x, 0, 2 Pi}, 
PlotLegends -> {"Sin", "Cos"}]
Plot[Table[f[[i]][x], {i, 1, 2}], {x, 0, 2 Pi}, 
PlotStyle -> {Red, Blue}, PlotLegends -> {"Sin", "Cos"}]
Plot[Table[f[[i]][x], {i, 1, 2}], {x, 0, 2 Pi}, 
PlotStyle -> {Red, Blue}, PlotLegends -> "AllExpressions"]

You forgot to include an Evaluate:

Plot[Evaluate@Table[f[[i]][x], {i, 1, 2}], {x, 0, 2 Pi}, 
 PlotStyle -> {Red, Blue}, PlotLegends -> "AllExpressions"]

which produces the correct result:

enter image description here

In general, if you are trying to Plot a Table in one step, you should always Evaluate the Table first, ie, Plot[Evaluate@Table[...], ...].

Brief explanation of behavior: By adding an Evaluate, you force symbolic evaluation of the Table first, and then Plot operates on the resulting table of two expressions, and then PlotLegends operates on the expressions, producing the correct pair of curves and labels.

In contrast, without the Evaluate, Plot sequentially evaluates Table[...] at the particular floating-point value currently being plotted, creating a sequence of lists of floating point numbers, which are then interpreted (I guess?) as a single function, thus causing both curves to be the same blue color. I have no idea what PlotLegends does, but I imagine it's similarly incorrect.

  • $\begingroup$ PlotLegends operates on a distinguishability criteria, the lines have to be visually distinct to be given a legend. $\endgroup$ – rcollyer Nov 9 '14 at 21:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.