Search code examples
rplotgraph3d

How to plot 3D graph of function of two variables in R


my task is to plot function of two variables f(x,y), where m is maturity and goes from 1 to 15. Here is my code:

f<-function(x,y)((x -y * ((1 - exp(-m / 4)) / (m / 4)) - 0.035 * ((1 - exp(-m / 4
  )) / (m / 4) - exp(-m / 4)))) 
z <- outer(x, y, f)
persp(x, y, z)
open3d()
plot3d(f,xlab = "x", ylab = "y", zlab = "m", ylim = c(-1, 1), xlim = c(-1, 1), zlim = c(1, 15))

But 3D grpah looks like this:enter image description here

Can anyone tell, where I made mistake?


Solution

  • You cannot pass a function as an argument of plot3D. Instead pass, your variable x, y and f(x,y). Here a simple reproducible example

    set.seed(5)
    x <- runif(100)
    m <- 4
    f<-function(x,y)((x -y * ((1 - exp(-m / 4)) / (m / 4)) - 0.035 * ((1 - exp(-m / 4
    )) / (m / 4) - exp(-m / 4)))) 
    z <- f(x,y)
    library(rgl)
    open3d()
    plot3d(x,y,z,xlab = "x", ylab = "y", zlab = "m")
    

    Which give you

    enter image description here

    if you another type of simbol to plot your data look at the type argument of plot3D. By default is set to "p" which means "points" but there are methods for "lines", "segments", sphere ecc (see ?plot3D):

    type
    For the default method, a single character indicating the type of item to plot. Supported types are: 'p' for points, 's' for spheres, 'l' for lines, 'h' for line segments from z = 0, and 'n' for nothing. For the mesh3d method, one of 'shade', 'wire', or 'dots'. Partial matching is used.