3
$\begingroup$

I'm trying to define my own collection of style commands so that I don't have to type them for all my Plots and ListPlots. The following works for ListPlot, but not for Plot.

Here is a minimal example:

mystyle = {Frame -> True, LabelStyle -> 14};
ListPlot[{1, 2}, mystyle]
Plot[x^2, {x, 1, 2}, mystyle]

I get the error:

Plot::nonopt: Options expected (instead of style) beyond position 2 in Plot[x^2,{x,1,2},style]. An option must be a rule or a list of rules.

Do you have any ideas why? Thanks for your answers

$\endgroup$
  • 2
    $\begingroup$ Plot[x^2, {x, 1, 2}, #] & @@ mystyle $\endgroup$ – corey979 Jan 19 '18 at 17:07
3
$\begingroup$

The error comes about because Plot has the attribute HoldAll. ListPlot does not have that attribute so it won't have that problem.

The variable mystyle will be replaced with its definition in ListPlot, whereas Plot will try to parse mystyle – the atom, not its definition – as a style. HoldAll prevents mystyle from being replaced with its definition.

To state this with code, ListPlot will see

ListPlot[{1, 2}, {Frame -> True, LabelStyle -> 14}]

whereas Plot will see

Plot[x^2, {x, 1, 2}, mystyle]

because mystyle is not evaluated in Plot since it has the HoldAll attribute.

You can allow the argument to be evaluated using Evaluate:

Plot[x^2, {x, 1, 2}, Evaluate[mystyle]]

A slightly more advanced technique is to inject the value of the variable with With:

With[{s = mystyle}, Plot[x^2, {x, 1, 2}, s]]

This latter technique does not require s to evaluate. What happens is that With takes the expression in its second argument and replaces the symbol s before it evaluates the expression. Hence, Plot is not evaluated before it has been rewritten as

Plot[x^2, {x, 1, 2}, {Frame -> True, LabelStyle -> 14}]
$\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.