# How to sample a function as Plot* functions do?

Suppose we have a hard to calculate function f. We plot it like e.g.

Plot3D[f[x,y],{x,-5,5},{y,-5,5},MaxRecursion->5,PlotPoints->30,PlotRange->All]


After some long calculation this gives us a nice image, it can be rotated and all, but suddenly we want to look at a density plot of f. We can of course repeat the whole long calculation with DensityPlot, but it's wasteful. We could instead have pre-calculated a table of values of f using Table, but this would imply homogeneous (or some manually-parametrized) grid, which can be an inefficient (or hard to implement) choice for many functions.

So what is needed is a way to sample the function as e.g. Plot3D would do it with given MaxRecursion and PlotPoints, but instead of putting the result into a graphics box, put it into a variable as a list of coordinates or whatever form suitable for List*Plot* family of functions. How can this be done?

Say for example :

 gr00 = Plot3D[
Sin[x y],
{x, -5, 5}, {y, -5, 5},
MaxRecursion -> 5, PlotPoints -> 30, PlotRange -> All]


The data, including the mesh, are the first element of GraphicsComplex[...] in gr00 :

gr00 // InputForm // Short


Then :

ListDensityPlot[gr00[[1, 1]]]


ListDensityPlot[gr00[[1, 1]], Mesh -> All]


You can even do a copy-paste of your graphic inside the ListDensityPlot, the data are not lost :

--> same result as above

• I like this, but it does depend on the internal, undocumented structure of an object – mikado Sep 4 '16 at 5:27
• @mikado The doc of Plot3D says : "Plot3D returns GraphicsComplex[data]]" without saying what is exactly data. You can use a more robust extraction of data with something like Cases[...,GraphicsComplex[___],{1,Infinity}]. The philosophy not do mix data and presentation (tick...) is stable on mathematica since the beginning. I think that the main risk is to have the Graphics[...] form instead of GraphicsComplex (see Normal[ComplexExpand[..]]), because GraphicsComplex[] was only introduced in 2007. So effectively, I only use this is interactive sessions. – andre314 Sep 4 '16 at 9:48