2
$\begingroup$

I'm trying to customize a plot function according to this code

myPlot[fun_, opts_: OptionsPattern[]] := Module[{cm = 72/2.54},
   Show[fun, FilterRules[{opts}, Options[Plot]]]
   ];
myPlot[Plot[Sin[x], {x, 0, 1}], ImageSize -> 2 cm]

To make this works (try to substitute 2 cm with 100 for instance) I have to ask FilterRules to look for Plot options instead of Show options. This sound strange to me but is not the main problem. The main problem is that cm is defined within the module and it is not evaluate properly when passed to ImageSize option.

Could someone suggest a way to fix this?

Thanks

$\endgroup$
2
  • $\begingroup$ To the non-main problem, evaluate Options[Show] and you'll see why you don't filter any $\endgroup$ – Jason B. Apr 13 '16 at 11:26
  • $\begingroup$ @JasonB: It gives me an empty list, though ImageSize is a Show option. See now your comment on Module vs Block and it works. Thanks! $\endgroup$ – Fabio Apr 13 '16 at 11:27
4
$\begingroup$

From the documentation,

Show allows any option that can be applied to graphics to be given.

But if you try to look at the options specific to Show you find none,

Options[Show]
(* {} *)

So you should use Options[Graphics] instead.

And to the main problem, it's a scoping thing. Module replaces all instances of cm with cm$232494 or some other random number. This is one case where you need Block instead. I recommend reading Leonid's post here for a great treatment of the various scoping constructs.

myPlot[fun_, opts_: OptionsPattern[]] := 
  Block[{cm = 72/2.54}, 
   Show[fun, FilterRules[{opts}, Options[Graphics]]]];
myPlot[Plot[Sin[x], {x, 0, 1}], ImageSize -> 18 cm]

enter image description here

One important caveat is that if you are defining myPlot as an exported function in a package, then it is necessary to export cm, otherwise it is in the mypackage`Private`cm context. Thanks to Kuba for pointing this out.

$\endgroup$
0

Your Answer

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

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