3dplots.R

nesau — Mar 5, 2014, 11:01 AM

# this code will plot a 3d function f
plot3d <- function(f,detail=30) {
  x <- seq(-10,10,length=detail)
  y <- x
  z <- outer(x,y,f)
  # if the element of z does not exist make it into a 1
  z[is.na(z)] <- 1
  # to change the background color of the plot use 
  op <- par(bg="white")
  # phi and theta are used to rotate the view of the plot shown
  # expand applies an expansion factor to the z coordinates  
  # to show number of axis, use ticktype="detailed"
  # xlab, ylab and zlab can still be used
  # shade changes the color slightly, default~0.10
  # use shade=0.75 for instance
  persp(x,y,z,theta=30,phi=30, expand=0.5, col="lightblue")
}

# rotated sinc function
f <- function(x,y) {
  r = sqrt(x^2+y^2)
  # the last expression of a function is returned by default
  10*sin(r)/r
}

# hyperbolic parabolid
g <- function(x,y) {
  a = 3
  b = 2
  x^2/a^2 + y^2/b^2
}

# ellipsoid
h <- function(x,y) {
  a = 1
  b = 1
  1 - x^2/a^2 - y^2/b^2
}

plot3d(f)

plot of chunk unnamed-chunk-1

plot3d(g)

plot of chunk unnamed-chunk-1