3

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?

soandos
  • 1,030
  • 8
  • 20
egwene sedai
  • 2,355
  • 16
  • 24
  • 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 Jan 06 '15 at 02:39
  • 2
    ... or foo2 = Plot[{Re[#], Im[#]}, #2, PlotRange -> All, ##3] &;? – kglr Jan 06 '15 at 02: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]"). – egwene sedai Jan 06 '15 at 02:46
  • @kguler foo2 works perfectly. – egwene sedai Jan 06 '15 at 02:48
  • 1
    @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 ;) – SquareOne Jan 09 '15 at 11:03

2 Answers2

3

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}]

enter image description here

  • 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:

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
1
ClearAll[foo];
foo = Plot[{Re[#], Im[#]}, #2, PlotRange -> All, ##3] &;

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

enter image description here

kglr
  • 394,356
  • 18
  • 477
  • 896
  • 1
    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. – Mr.Wizard Jan 22 '15 at 18:48