I'd like to create a custom function that does essentially the same as a core function of mathematica but uses different default settings.
Example: I want a Plot function that uses Mathematica's core Plot
function but uses different default settings. I don't want to use SetOptions[Plot, ...]
because I don't want to override anything for the core Plot function. Instead of this I want to build a custom function PlotFramed[x^2,{x,-5,5}]
that points to Plot[x^2, {x,-5,5}, Frame->True, GridLines->Automatic]
.
I also want the function to be able to override my default settings. So PlotFramed[x^2, {x,-5,5}, GridLines->None]
should return the results from Plot[x^2, {x,-5,5}, Frame->True, GridLines->None]
.
And I want to use additional options that are not set by default as in the normal Plot function. So PlotFramed[x^2, {x,-5,5}, PlotStyle->Dashed]
should point to Plot[x^2, {x,-5,5}, Frame->True, GridLines->Automatic, PlotStyle->Dashed]
.
The reason for this is that when writing reports (in LaTeX) I have to add several options to the plot function to make the font-size bigger, add a grid, etc pp. Using the idea above I could write a custom Plot function that I can use when generating output for the report and otherwise use Mathematica's core function since everything is fine with it when working inside Mathematica.
Can anyone tell me how to do this? This would be awesome. Thanks in advance!
Answer
I have proposed a different solution exactly for this sort of situations. You don't have to create a new function with it, but rather you create an environment such that when your function is executed in it, the options you desire get passed to it. So, it is the same idea, but automated one step further.
Here is the (modified) code for the option configurator:
ClearAll[setOptionConfiguration, getOptionConfiguration,withOptionConfiguration];
SetAttributes[withOptionConfiguration, HoldFirst];
Module[{optionConfiguration},
optionConfiguration[_][_] = {};
setOptionConfiguration[f_, tag_, {opts___?OptionQ}] :=
optionConfiguration[f][tag] = FilterRules[{opts}, Options[f]];
getOptionConfiguration[f_, tag_] := optionConfiguration[f][tag];
withOptionConfiguration[f_[args___], tag_] :=
optionConfiguration[f][tag] /. {opts___} :> f[args, opts];];
Here is how one can use it: first create the option configuration with some name (e.g. "framed"):
setOptionConfiguration[Plot, "framed",
{Frame -> True, GridLines -> Automatic, PlotStyle -> Dashed}]
Now you can use it:
withOptionConfiguration[Plot[x^2, {x, -5, 5}], "framed"]
You can also create an environment short-cut:
framed = Function[code, withOptionConfiguration[code, "framed"], HoldFirst];
and then use it as
framed@Plot[x^2, {x, -5, 5}]
to get the same as before.
The advantage of this approach is that you can use the same tag (name) for the option configuration, for many different functions, at once.
Comments
Post a Comment