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[]] := 
  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?

  • 4
    $\begingroup$ Try myPlot[f_, opts : OptionsPattern[{myPlot, Plot}]] := (* stuff *). $\endgroup$ – J. M. is away May 11 '17 at 1:27
  • $\begingroup$ @J.M. Great, works, Thank you so much! +1 $\endgroup$ – matheorem May 11 '17 at 1:40
  • 4
    $\begingroup$ I prefer using Options[myPlot] = Join[Options[Plot], {cc -> 10}] so that I see all possible options listed when I use Options[myPlot]. $\endgroup$ – Carl Woll May 11 '17 at 2:01
  • $\begingroup$ 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]]] $\endgroup$ – matheorem May 11 '17 at 6:20
  • 1
    $\begingroup$ Related: mathematica.stackexchange.com/a/140912/12 $\endgroup$ – Szabolcs May 11 '17 at 7:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.