5

I found sometimes, I need both OptionValue to get a customized default value and FilterRules in a function.

Below is an illustration of the problem

Options[myPlot] = {cc -> 10};
myPlot[f_, opts : OptionsPattern[]] := 
 Module[{},
  Plot[f[x] OptionValue[cc], {x, 1, 2}, 
   Evaluate[FilterRules[{opts}, Options[Plot]]], PlotRange -> All]
  ]

If I run myPlot[Sin, ImageSize -> 600], though the result is fine. However, it will warns me

OptionValue::nodef: Unknown option ImageSize for myPlot.

Trace shows the problems is when executing OptionValue[myPlot, {ImageSize -> 600}, cc] internally. I can't figure out a way to get rid of this warning message instead of using Quiet. So I am asking here if I am using OptionValue the wrong way?

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
matheorem
  • 17,132
  • 8
  • 45
  • 115
  • 7
    Try myPlot[f_, opts : OptionsPattern[{myPlot, Plot}]] := (* stuff *). – J. M.'s missing motivation May 11 '17 at 01:27
  • @J.M. Great, works, Thank you so much! +1 – matheorem May 11 '17 at 01:40
  • 5
    I prefer using Options[myPlot] = Join[Options[Plot], {cc -> 10}] so that I see all possible options listed when I use Options[myPlot]. – Carl Woll May 11 '17 at 02:01
  • Hi, @CarlWoll Your approach is subtly different from J.M. If you want some customized default Plot option for example PlotRange -> {0, 10}. Then you can only put them in Join[{PlotRange -> {0, 10}}, Options[Plot], {cc -> 10}] right before Options[Plot]. However, in J.M. solution, we can put it inside Plot, but have to be sure it is after Evaluate[FilterRules[{opts}, Options[Plot]]] – matheorem May 11 '17 at 06:20
  • 1
    Related: https://mathematica.stackexchange.com/a/140912/12 – Szabolcs May 11 '17 at 07:24

0 Answers0