2
$\begingroup$

I have written a function Fun as below:

Fun[x_Symbol, xrange_, imageSize_, axeslabel_] :=
 Plot[x^2, {x, xrange[[1]], xrange[[2]]}, 
   ImageSize -> imageSize, 
   AxesLabel -> axeslabel]

Fun[x, {-1, 2}, 400, {"x", "y"}]

enter image description here

However, I'd like to rewrite it to use OptionsPattern

RewriteFun[x_Symbol, OptionsPattern[Plot]] := 
  Plot[x^2, {x, -1, 2}, 
    ImageSize -> OptionValue[ImageSize], 
    AxesLabel -> OptionValue[AxesLabel]]

RewriteFun[x, ImageSize -> 400, AxesLabel -> {"x", "y"}]

enter image description here

I have two problems.

  • I don't know how to deal with an option like {x, xmin, xmax}.

  • I don't how to get the kind of syntax coloring the varible x has in Plot[x^2, {x, -1, 2}].

enter image description here

So my question is: How do I revise the RewriteFun to solve my problems?

$\endgroup$
2
  • 2
    $\begingroup$ An argument of the form {x, xmin, xmax} isn't a option for Plot. It is Plot's required second argument. You must add a required second argument to your function to handle it. $\endgroup$
    – m_goldberg
    Commented Aug 1, 2014 at 12:50
  • $\begingroup$ (1) See 1446 and 54956. (2) Presumably you mean the argument {x, xmin, xmax}? $\endgroup$
    – Michael E2
    Commented Aug 1, 2014 at 13:28

2 Answers 2

4
$\begingroup$

Here's my interpretation of the question:

ClearAll[RewriteFun];
SetAttributes[RewriteFun, HoldAll];
Options[RewriteFun] = Options[Plot];
SyntaxInformation[
   RewriteFun] = {"ArgumentsPattern" -> {{_, _, _}, 
     OptionsPattern[Plot]}, "LocalVariables" -> {"Plot", {1}}};
RewriteFun[dom : {x_, _, _}, OptionsPattern[]] := 
 Plot[x^2, dom, ImageSize -> OptionValue[ImageSize], 
  AxesLabel -> OptionValue[AxesLabel]]

RewriteFun[{t, -2, 1}, ImageSize -> 150, AxesLabel -> {"x", "y"}]

Mathematica graphics

$\endgroup$
2
$\begingroup$

You could do the following:

Options[fun] = {ImageSize -> 400, AxesLabel -> {"x", "y"}, xmin -> -1, xmax -> 2};

fun[x_Symbol, OptionsPattern[]] :=
 Plot[x^2, {x, OptionValue@xmin, OptionValue@xmax}, 
  ImageSize -> OptionValue@ImageSize, 
  AxesLabel -> OptionValue@AxesLabel]

fun[z, xmin -> -2, AxesLabel -> {"z", "y"}]

enter image description here

You could even turn the symbol (or the whole function) into an option:

Options[fun] = {ImageSize -> 400, AxesLabel -> {"x", "y"}, symbol -> x, xmin -> -1, xmax -> 2};

fun[OptionsPattern[]] :=
 Block[{sym = OptionValue@symbol},
  Plot[sym^2, {sym, OptionValue@xmin, OptionValue@xmax},
   ImageSize -> OptionValue@ImageSize,
   AxesLabel -> OptionValue@AxesLabel]]
$\endgroup$
1
  • $\begingroup$ @Öskå Quotation: "I don't know how to deal with an option like {x, xmin, xmax}." $\endgroup$
    – eldo
    Commented Aug 1, 2014 at 13:15

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