2
$\begingroup$

I need to plot many function pairs $\{f_i(x),f_i(x) + e h_i(x)\}$, where $e$ is a small parameter, say 0.05, in a single plot with a legend generated using PlotLegends. Here is a minimalist example of what the code would look like for just two pairs:

Block[{func, h = e Sin[2 Pi x], eval = 0.05}, func = {x, x + h, x^2, x^2 + h}; Plot[Evaluate[func /. e -> eval], {x, 0, 1}, PlotLegends -> "Expressions", PlotLabel -> "e = " <> ToString[eval]]] 

However, the parameter $e$ is evaluated in the legend, while I prefer to have only the symbol $e$ there, not its value, which in turn must be displayed by PlotLabel. I tried using an explicit list of expressions as the value of PlotLegends option:

Block[{func, h = e Sin[2 Pi x], eval = 0.05}, func = {x, x + h, x^2, x^2 + h}; Plot[Evaluate[func /. e -> eval], {x, 0, 1}, PlotLegends -> func, PlotLabel -> "e = " <> ToString[eval]]] 

This leaves $e$ unevaluated, but sorts the expressions in the legends, which is also undesirable. Any ideas?

$\endgroup$
1
  • 3
    $\begingroup$ PlotLegends -> HoldForm /@ func $\endgroup$ Commented Apr 21 at 19:09

1 Answer 1

3
$\begingroup$

Bob Hanlon beat me to it, but I'll add this anyway. I think With is more appropriate that Block, is clearer to read, and allows simpler control of evaluation sequence. But of course that's just a matter of opinion.

With[ {rawh = e Sin[2 Pi x], eval = .05}, {heldfns = HoldForm /@ {x, x + rawh, x^2, x^2 + rawh}}, {plotfns = ReleaseHold[heldfns /. e -> eval]}, Plot[plotfns, {x, 0, 1}, PlotLegends -> heldfns, PlotLabel -> StringForm["e = ``", eval]]] 
$\endgroup$
3
  • $\begingroup$ Many thanks to Bob Hanlon and lericr. Both solutions give exactly what I need. And indeed, I originally started with With, only then reluctantly switched to Block. So I agree that With is more appropriate than Block. $\endgroup$ Commented Apr 21 at 20:09
  • $\begingroup$ By the way, is the With[{x=a},{y=x},...,body] syntax used by lericr's solution documented? Syntax coloring suggests that it is not, and I couldn't find it in the documentation center, but it works. How safe is it to rely on undocumented features? $\endgroup$ Commented Apr 22 at 11:46
  • $\begingroup$ @hlediks I have never seen this officially documented. I learned about it from this site. I can't find the thread now (searching for "With" is unsatisfying). If you don't want to use this undocumented feature, and you don't want many nested Withs, then you can certainly take a completely different approach, which is what I probably would do. That is, build functions to do the work of creating a plot-able function and its legend from some "template". It might only be worth it to you if you were doing this many times, however. $\endgroup$ Commented Apr 22 at 16:44

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.