R - 分别在 3d 中绘制两个二元法线及其轮廓 [英] R - Plotting two bivariate normals in 3d and their contours respectively

查看:75
本文介绍了R - 分别在 3d 中绘制两个二元法线及其轮廓的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在玩 MASS 包,可以简单地使用 image 和 par(new=TRUE) 绘制两个二元法线,例如:

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!

推荐答案

也许你可以使用 rgl 库.它允许您创建交互式 3d 图.

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

如果您想绘制两个曲面之间的差异,则可以执行以下操作.

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)

这篇关于R - 分别在 3d 中绘制两个二元法线及其轮廓的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆