R - Plotting two bivariate normals in 3d and their contours respectively

JEquihua picture JEquihua · Mar 13, 2013 · Viewed 11.9k times · Source

I have been playing around with the MASS package and can plot the two bivariate normal simply using image and par(new=TRUE) for example:

# lets first simulate a bivariate normal sample
library(MASS)
bivn <- mvrnorm(1000, mu = c(0, 0), Sigma = matrix(c(1, .5, .5, 1), 2))
bivn2 <- mvrnorm(1000, mu = c(0, 0), Sigma = matrix(c(1.5, 1.5, 1.5, 1.5), 2))

# now we do a kernel density estimate
bivn.kde <- kde2d(bivn[,1], bivn[,2], n = 50)
bivn.kde2 <- kde2d(bivn2[,1], bivn[,2], n = 50)

# fancy perspective
persp(bivn.kde, phi = 45, theta = 30, shade = .1, border = NA)
par(new=TRUE)
persp(bivn.kde2, phi = 45, theta = 30, shade = .1, border = NA)

Which doesn't look very good, I guess I have to just play around with the axis and stuff. But if I try a similar approach with the contour the plots do not overlap. They are simply replaced:

# fancy contour with image
image(bivn.kde); contour(bivn.kde, add = T)
par(new=TRUE)
image(bivn.kde2); contour(bivn.kde, add = T)

Is this the best approach to what I want or am I just making it hard on myself? Any suggestions are welcome. Thank you!

Answer

Chinmay Patil picture Chinmay Patil · Mar 14, 2013

Perhaps you can use rgl library. It allows you to create interactive 3d plots.

require(rgl)

col1 <- rainbow(length(bivn.kde$z))[rank(bivn.kde$z)]
col2 <- heat.colors(length(bivn.kde2$z))[rank(bivn.kde2$z)]
persp3d(x=bivn.kde, col = col1)
with(bivn.kde2, surface3d(x,y,z, color = col2))

enter image description here

If you want to plot difference between two surfaces then you can do something like below.

res <- list(x = bivn.kde$x, y = bivn.kde$y, z = bivn.kde$z - bivn.kde2$z)
col3 <- heat.colors(length(res$z))[rank(res$z)]
persp3d(res, col = col3)

enter image description here