简体   繁体   中英

How to plot dynamic and rotatable 3D of the density function for the bivariate normal distribution in R

install.packages("scatterplot3d")
library(scatterplot3d)
library("mvtnorm")
x1 <- x2 <- seq(-10, 10, length = 51)
dens <- matrix(dmvnorm(expand.grid(x1, x2),
                   sigma = rbind(c(3, 2), c(2, 3))),
           ncol = length(x1))
s3d <- scatterplot3d(x1, x2,
                 seq(min(dens), max(dens), length = length(x1)),
                 type = "n", grid = FALSE, angle = 70,
                 zlab = expression(f(x[1], x[2])),
                 xlab = expression(x[1]), ylab = expression(x[2]),
                 main = "Bivariate normal distribution")
text(s3d$xyz.convert(-1, 10, 0.07),
labels = expression(f(x) == frac(1, sqrt((2 * pi)^n *phantom(".") * det(Sigma[X]))) *     
phantom(".") * exp * {bgroup("(", - scriptstyle(frac(1, 2) * phantom(".")) *
(x - mu)^T * Sigma[X]^-1 * (x - mu), ")")}))
text(s3d$xyz.convert(1.5, 10, 0.05),
labels = expression("with" * phantom("m") *mu == bgroup("(", atop(0, 0), ")") * 
phantom(".") * "," *phantom(0) *
{Sigma[X] == bgroup("(", atop(3 * phantom(0) * 2,2 * phantom(0) * 3), ")")}))
for(i in length(x1):1)
s3d$points3d(rep(x1[i], length(x2)), x2, dens[i,], type = "l")
for(i in length(x2):1)
s3d$points3d(x1, rep(x2[i], length(x1)), dens[,i], type = "l")

How to plot dynamic and rotatable 3D of the density function for the bivariate normal distribution in R? Thanks

How to plot the second plot in http://personal.kenyon.edu/hartlaub/MellonProject/Bivariate2.html

 library(emdbook)
 library(rgl)
 curve3d(dmvnorm(c(x,y),mu=c(0,0),Sigma=diag(2)),
         sys3d="rgl",col="blue",
         xlim=c(-3,3),ylim=c(-3,3))

If you want a wireframe plot then

 curve3d(dmvnorm(c(x,y),mu=c(0,0),Sigma=diag(2)),
         sys3d="rgl",front="line",back="line",
         xlim=c(-3,3),ylim=c(-3,3))

should work (see ?rgl.material ).

If you want to add additional elements to this plot, see (for example) ?lines3d , ?points3d (you will need to compute the coordinates yourself: the ellipse package may be useful for this).

Another method plot 3D:

library(mnormt)               
mu <- c(0,0)
sigma <- matrix(c(1,0,0,1),2,2)                                
x<-seq(-4,4,0.1)
y<-seq(-4,4,0.1)
f<-function(x,y){dmnorm(cbind(x,y), mu, sigma)}
z<-outer(x,y,f)
persp(x,y,z, box=T,axes=T, ticktype="detailed", theta=40,phi=0)
persp(x,y,z, theta=30,phi=50)
persp(x,y,z, theta=100,phi=40,col="blue")
wireframe(z)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM