I would like to customize the function DensityPlot
and use it in a package as a function called MyDensityPlot
:
The functions looks like that in a package MyPackage.m
:
BeginPackage["MyPackage`"];
MyDensityPlot::usage=""
Begin["Private`"]
Options[MyDensityPlot]:=Options[DensityPlot];
MyDensityPlot[fn_,range_,options:OptionsPattern[]] :=
Module[{ii, p1, externalSymbol, localx,localy},
externalSymbol = With[{currentContextQ=Context@#===$Context&},DeleteDuplicates@Cases[{fn},_Symbol?currentContextQ,Infinity]];
ii = Unevaluated[fn] /. externalSymbol[[1]] :> localx/.externalSymbol[[2]]:>localy;
p1 = DensityPlot[ii, {localx,localy} \[Element] Disk[{0,0},range],options]
]//Quiet;
End[];
I used the answer of the following question: Pass function or formula as function parameter in order to pass the function fn
as an argument.
Then, from this answer:
Extracting variables from an expression, I extract, in the package context, the variable names of the function fn
and replace them by local variables localx
localy
for the plot.
It's working but I think it's not a good code, in particular if the function fn
as just one variable, externalSymbol[[2]]
wouldn't exist :
MyDensityPlot[x, 1]
Part::partw: Part 2 of {x} does not exist. >>
But the graphic will be displayed anyway. I'm then using a //Quiet;
at the end of the function... but it's really circumvent the problem. So if you have any suggestions to improve this function definition.
Thank you for your help.
{MyDensityPlot[Sin[a^2 - b], 5, PlotPoints -> 50], MyDensityPlot[Sin[f], 5], MyDensityPlot[3, 5], MyDensityPlot[a + b + c, 5]}
make sense. Would you rather the function not make a plot at all if the list of variables is not equal to 2? $\endgroup$MyDensityPlot[a+b+c,5]
, the plot fails, as inDensityPlot
built-in function. So yep, the behaviour should be as inDensityPlot
. HoweverDensityPlot
doesn't generate an error when there is only one variable, andMyDensityPlot
does, thus my question about more efficient code maybe.. ? $\endgroup$