0
$\begingroup$

I have a code in which I read data from a file and perform a number of fits. I wish to plot these fits on a single plot and add a legend which labels each line with a value which is saved in a list (of the same length as the number of fits). However, PlotLegends is only labelling one of the lines. As a simple example, if I run

leg = {1, 2};
Plot[{x, x^2}, {x, 0, 2}, PlotLegends -> leg]

it produces

enter image description here

The legends are applied correctly. However, if I define the list of functions beforehand, it doesn't work. If I now run

fs = {x, x^2};
Plot[fs, {x, 0, 2}, PlotLegends -> leg]

I get

enter image description here

There is no issue if I do a ListPlot however:

lfs = Table[Table[{x, x^j}, {x, 0, 2, 0.1}], {j, 1, 2}];
ListPlot[lfs, PlotLegends -> leg]

enter image description here

I suspect I am failing to understand how Mathematica interprets symbols such as x when defined the way I have defined here. For the purpose of my application, I am starting with discrete data points such as defined in lfs above, fitting curves, and then plotting:

fits = {Fit[lfs[[1]], {1, x}, x], Fit[lfs[[2]], {1, x, x^2}, x]};
Plot[fits, {x, 0, 2}, PlotLegends -> leg]

enter image description here

But again I have the same issue as before.

$\endgroup$
  • 2
    $\begingroup$ It works correctly in 11.3. What version are you using? $\endgroup$ – ulvi Apr 20 '18 at 7:53
  • $\begingroup$ I'm voting to close this question as off-topic because I cannot reproduce the problem the user is experiencing; I suspect it is being caused by corrupted lexical elements in the OP's Mathematica notebook. $\endgroup$ – m_goldberg Apr 21 '18 at 1:44
  • $\begingroup$ Could you please elaborate? This is a problem I consistently have across all of my notebooks. $\endgroup$ – Kai Apr 21 '18 at 2:10
1
$\begingroup$
Plot[fs, {x, 0, 2}, PlotLegends -> leg]

works in v11.3, but indeed produces

enter image description here

in v10.4. The solution is Evaluate:

Plot[Evaluate @ fs, {x, 0, 2}, PlotLegends -> leg]

enter image description here

$\endgroup$

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.