[R] Add lines (contours) to lattice wireframe plot

Andrej andrej.kastrin at gmail.com
Sat Feb 20 01:24:53 CET 2010


Hi,

I draw a surface corresponding to bivariate density of independent
variables (rho=0) using persp(). Then I add a contour line (i.e.,
circle in my case) at a particular density. Below is a minimal example
of what I have so far.

# Bivariate density
dnorm2d <- function(x, y, rho = 0) {
  xoy = (x^2 - 2 * rho * x * y + y^2)/(2 * (1 - rho^2))
  density = exp(-xoy)/(2 * pi * sqrt(1 - rho^2))
  density
}
# Variables
x <- seq(from = -3, to = 3, length = 40)
y <- seq(from = -3, to = 3, length = 40)
z <- outer(X = x, Y = y, FUN = dnorm2d)
# Perspective plot
persp(x = x, y = y, z = z) -> res
# Add contour
phi <- seq(0, 2*pi, length=200)
r <- 2
xr <- r * cos(phi)
yr <- r * sin(phi)
lines(trans3d(xr, yr, dnorm2d(xr, yr), res))

Unfortunately, it's difficult to customize perspective plot, so I try
wireframe in lattice instead:

library(lattice)
g <- expand.grid(x=seq(from=-3, to=3, length=40), y=seq(from=-3, to=3,
length=40))
g$z <- dnorm2d(g$x, g$y)
wireframe(z~x*y, data=g)

Could you give me some advice how to add lines (i.e., circle) on
lattice graphics.

Thanks for any suggestion.

Best, Andrej



More information about the R-help mailing list