# Forward function arguments to built-in Plot[]

Suppose I need to write a function to plot the real and imaginary part of some function (just an example). I want to define a function foo so that foo[f[t],{t,0,10},PlotRange->All,(some other plot options)] essentially calls

Plot[{Re[f[t]],Im[f[t]]},{t,0,10},PlotRange->All,(some other plot options)]


How to achieve that with, say, pattern matching?

• Does this give what you need: ClearAll[foo]; SetAttributes[foo, HoldFirst]; foo[f_[t_], {t_, tmin_, tmax_}, opts : OptionsPattern[]] := Plot[{Re[f[t]], Im[f[t]]}, {t, tmin, tmax}, PlotRange -> All, opts]?
– kglr
Commented Jan 6, 2015 at 2:39
• ... or foo2 = Plot[{Re[#], Im[#]}, #2, PlotRange -> All, ##3] &;?
– kglr
Commented Jan 6, 2015 at 2:44
• @kguler thanks, but foo[Sin[t] + I*Cos[t], {t, 0, 10}, PlotRange -> All] does not work on my machine (output is exactly "foo[Sin[t] + I*Cos[t], {t, 0, 10}, PlotRange -> All]"). Commented Jan 6, 2015 at 2:46
• @kguler foo2 works perfectly. Commented Jan 6, 2015 at 2:48
• @kguler The foo definition given by @kguler will actually work if you just replace {Re[f[t]], Im[f[t]]} with Evaluate@{Re[f[t]], Im[f[t]]}. These comments should be posted as an answer ;) Commented Jan 9, 2015 at 11:03

I propose this:

SetAttributes[myPlot, HoldAll]

myPlot[x_, args__, opts : OptionsPattern[Plot]] :=
Plot[{Re@x, Im@x}, args, opts, PlotRange -> All]


Test:

myPlot[Sin[t] + I*Cos[t], {t, 0, 10}]


• HoldAll is used to mimic the evaluation behavior of Plot.

• OptionsPattern[Plot] is used to define the valid options as being those of Plot.

• opts is placed before PlotRange -> All so that an explicit PlotRange will overrule the default; this is usually desired.

For a longer example of option customization please see:

Also related:

ClearAll[foo];
foo = Plot[{Re[#], Im[#]}, #2, PlotRange -> All, ##3] &;

foo[Sin[t] + I*Cos[t], {t, 0, 10}, PlotStyle -> Thick]


• This is terse, and you know I like terse, but there is a problem with it as-written: you lose the HoldAll behavior of Plot so this will break if e.g. t has a global value. Commented Jan 22, 2015 at 18:48