4
$\begingroup$

I have a code which goes like this:

Plot[{Sin[x], Sin[2 x], Sin[3 x]}, {x, 0, 2 Pi}, 
 PlotLegends -> "Expressions"]
Plot[{Sin[x], Sin[2 x], Sin[3 x]}, {x, 0, 2 Pi}, 
 PlotLegends -> {"This is for x", "This is for 2x", "This is for 3x"}]

which produces the plots:

enter image description here

I need to write legends in such a way that it takes, say, 1st expression and then besides that it writes "This is for x" (same for 2nd and 3rd). How can we do this in Mathematica?

I tried with this code (not sure why 😀!):

Plot[{Sin[x], Sin[2 x], Sin[3 x]}, {x, 0, 2 Pi}, 
 PlotLegends -> {"Expressions", {"This is for x", "This is for 2x", 
    "This is for 3x"}}]

But, I am getting another set of legend down the figure: enter image description here

How can one accomplish this?

Mathematica version: 12.1

Thanks in advance.

$\endgroup$

1 Answer 1

5
$\begingroup$
plot  = Plot[{Sin[x], Sin[2 x], Sin[3 x]}, {x, 0, 2 Pi}, 
  PlotLegends -> "Expressions"];

You can post-process the output to replace legend labels with the desired strings:

plot /. HoldPattern[p : HoldForm[_[a_]]] :> Row[{p, " -- This is for ", HoldForm @a}]

enter image description here

SeedRandom[1]
With[{ri = RandomInteger[{3, 7}]}, 
  Plot[{Sin[x], Sin[ri x + x^2], Sin[ri x]}, {x, 0, 2 Pi}, 
   PlotLegends -> "Expressions"]] /. 
 HoldPattern[p : HoldForm[_[a_]]] :> Row[{p, " -- This is for ", HoldForm @ a}]

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.