如何绘制R中二元正态分布的密度函数的动态和可旋转3D

时间:2014-06-11 16:56:28

标签: r plot

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")

如何绘制R中二元正态分布的密度函数的动态和可旋转3D?谢谢

如何在http://personal.kenyon.edu/hartlaub/MellonProject/Bivariate2.html

中绘制第二个图

2 个答案:

答案 0 :(得分:3)

 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))

如果你想要一个线框图,那么

 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))

应该有用(见?rgl.material)。

如果您想在此图中添加其他元素,请参阅(例如)?lines3d?points3d(您需要自己计算坐标:ellipse包可能有用为此)。

答案 1 :(得分:0)

另一种绘制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)