2
$\begingroup$

Consider a function myFunc with options

Options[myFunc] = {TellNoOne->True}; (* myFunc has some options *)

myFunc[a_, b_, OptionsPattern[]] := 
  Module[{},
    (* Do stuff with OptionValue[TellNoOne] and plot result *)
    ListPlot[{a,b}, moreOptions] (* want to pass some options to ListPlot here *)]

I wish to pass options that will target myFunc, like TellNoOne, and I also want to be able to pass any option to ListPlot that it accepts such as PlotRange->All and others.

Function call example:

myFunc[1, 3, TellNoOne -> False, PlotRange -> All, Joined -> True, Framed -> True]

How can I pass myFunc is own options plus others for ListPlot?

$\endgroup$
4
  • 1
    $\begingroup$ Does myFunc[a_, b_, OptionsPattern[Join[Options[myFunc], Options[ListPlot]]]] := (* stuff *) work for you? $\endgroup$ Nov 3, 2017 at 11:22
  • $\begingroup$ You can use FilterRules like in this example from the documentation FilterRules[{PlotRange -> 3, MaxIterations -> 5}, Options[Plot]] $\endgroup$
    – ercegovac
    Nov 3, 2017 at 11:22
  • $\begingroup$ I thinks this is what you ask and more: mathematica.stackexchange.com/q/82626/5478 $\endgroup$
    – Kuba
    Nov 3, 2017 at 11:30
  • $\begingroup$ Does this answer your question? Let us know if it's a suitable duplicate. $\endgroup$
    – Szabolcs
    Nov 3, 2017 at 11:31

1 Answer 1

1
$\begingroup$

Here is a very general approach in which we give myFunc default options from ListPlot as well as it own option "Tell", which when given will cause a story :-) to be printed.

ClearAll[myFunc]
Options[myFunc] = {PlotStyle -> Red, Joined -> True, "Tell" -> False};
myFunc[data_List, opts : OptionsPattern[]] :=
  (If[OptionValue[myFunc, FilterRules[{opts}, Options[myFunc]], "Tell"], 
     Print["Once upon a time in a galaxy far, far away ...."]];
   ListPlot[data, FilterRules[{opts, Options[myFunc]}, Options[ListPlot]]])

Tests

Test data

data = Table[Sin[2 π t], {t, 0, 1, .02}];

Default options

myFunc[data]

plot1

Giving the "Tell" option

myFunc[data, "Tell" -> True]

plot2

Over-riding myFunc's specified graphics options defaults and adding an additional graphics option

myFunc[data, PlotStyle -> Blue, Joined -> False, DataRange -> {0, 1}]

plot3

$\endgroup$
1
  • $\begingroup$ This works just fine. Thank you. I see by the other answers that there are a few variations on how it can be done. $\endgroup$
    – A. Vieira
    Nov 8, 2017 at 11:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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