The curve
function in R provides a simple way to plot a function. For example, this will plot a straight line
f1 <- function(x) x
curve(f1, from=-1, to=1)
Is there an equivalent function in R which takes a function with two argument (e.g., x
and y
) and ranges for both variables and produces a 3D plot?
For example, imagine I had the following function
f2 <- function(x, y) x + y
Is there a command similar to the following?
curve_3d(f2, x_range=c(-1, 1), y_range=c(-1, 1))
You can have an interactive plot with the
plot3Drgl
package.See
curve3d()
inpackage:emdbook
, which is a wrapper forwireframe()
,persp3d()
, and more.The
surface3d
function in package:rgl looks like a good match. It would be very simple to create a wrapper that would take your function, create an x-y set of vectors withseq()
and then pass those vectors toouter
with your f2 as the FUN argument, and then callsurface3d
.There is also a
persp3d
which the authors (Duncan Murdoch and perhaps others) say is "higher level" and it does appear to add axes by default which surface3d does not.Now that I think about it further, you could have done something similar with
persp()
orwireframe()
. The "trick" is using outer(..., FUN=fun). And as I think about it even further ... the ability to use it withouter
depends on it being composed of all vectorized operations. If they were not vectorized, we would need to rewrite withVectorize
ormapply
.The
persp3d()
function can take a function as an argument. See?persp3d.function
.It allows two kinds of surface to be plotted: a function of
x
andy
as you want, and a parametric surface, wherex
,y
andz
are all functions of two other variables.For your example, it's as simple as
but of course you can add all sorts of frills, like having the colour depend on
z
, changing the range ofx
andy
, etc.