Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems passing options in specialized plot functions for Mathematica

This should be quick to an expert, but I'm relatively new at defining functions with options. Here is a schematic of what I've tried, I'll explain after showing the code:

MyPlotFunction[params_, optionalparameter_List:{1,2,3}, opts:OptionsPattern[]]:=
    Plot [ stuff, {x,0,1},  Evaluate@FilterRules[{opts},Options@Plot]];

Options[MyPlotFunction] = {  PlotRange->{-5,5}, Frame->True, ... other plot options};

There are four slight subtleties:

  1. I have an optional parameter in my function that needs to be a list of integers.
  2. I want the ability to call the function with any option of Plot, especially using values other than the default values specified in the third line.
  3. I want to have default values for some of the options.
  4. I potentially want to put other options in the function, so it is not guaranteed that all of the options should be passed through to plot.

But what I have above doesn't work. The default options I set are ignored, yet they appear in the ??MyPlotFunction information for my function. I'll give examples if you guys can't spot the error yet.

Edit: Examples that doesn't work:

  1. SimplePlot[t_,opts:OptionsPattern[{PlotRange->{-4,4},Frame->True}]]:= Plot[2x+t,{x,0,1},opts]; Fails, the default option is ignored.

  2. SimplePlot[t_,opts:OptionPattern[]]:= Plot[2x+t],{x,0,1},opts]; Options[SimplePlot] = {PlotRange->{-4,4},Frame->True}; Fails, the default option is ignored.

  3. SimplePlot[t_,opts__:{PlotRange->{-4,4},Frame->True}]:= Plot[2x+t,{x,0,1},opts]; Default options work with a bare call, but if one of these options or any other plot option is overridden the remaining defaults are lost.

like image 473
deemaregee Avatar asked Dec 16 '11 22:12

deemaregee


1 Answers

OptionsPattern[] only catches the options that are passed in, so you need to explicitly include any non-default option settings, say by using something like:

FilterRules[{opts, Options[MyPlotFunction]}, Options@Plot]

Here's a simple example:

Options[MyPlotFunction] = {PlotRange -> {-5, 5}, Frame -> True};

MyPlotFunction[params_, optionalparameter_List: {1, 2, 3}, 
  opts : OptionsPattern[MyPlotFunction]] := 
 Plot[optionalparameter, {x, 0, 1}, 
  Evaluate@FilterRules[{opts, Options[MyPlotFunction]}, Options@Plot]]

enter image description here

like image 112
Brett Champion Avatar answered Oct 23 '22 20:10

Brett Champion