用ggplot2绘制多元高斯等高线

时间:2016-03-25 14:13:28

标签: r ggplot2

我试图用具有已知均值和协方差的2D高斯分布来增加具有轮廓的图。理想情况下,我只需要指定函数,它就会在2D中绘制(如stat_function,除了2维)。我可以通过生成概率网格来geom_raster。我可以用某种方式使用geom_contour2d吗?

m <- c(.5, -.5)
sigma <- matrix(c(1,.5,.5,1), nrow=2)
data.grid <- expand.grid(s.1 = seq(-3, 3, length.out=200), s.2 = seq(-3, 3, length.out=200))
q.samp <- cbind(data.grid, prob = mvtnorm::dmvnorm(data.grid, mean = m, sigma = sigma))
ggplot(q.samp, aes(x=s.1, y=s.2)) + 
    geom_raster(aes(fill = prob)) +
    coord_fixed(xlim = c(-3, 3), ylim = c(-3, 3), ratio = 1)

enter image description here

2 个答案:

答案 0 :(得分:2)

我正在咆哮着看错2d的东西。您可以使用geom_contour并添加z美学来实现我想要的目标:

m <- c(.5, -.5)
sigma <- matrix(c(1,.5,.5,1), nrow=2)
data.grid <- expand.grid(s.1 = seq(-3, 3, length.out=200), s.2 = seq(-3, 3, length.out=200))
q.samp <- cbind(data.grid, prob = mvtnorm::dmvnorm(data.grid, mean = m, sigma = sigma))
ggplot(q.samp, aes(x=s.1, y=s.2, z=prob)) + 
    geom_contour() +
    coord_fixed(xlim = c(-3, 3), ylim = c(-3, 3), ratio = 1) 

enter image description here

答案 1 :(得分:1)

我会使用def treecomp(tree, list_of_funcs): ... return function F = treecomp(T, L) 包直接构造轮廓数据。这仍然需要单独调用来构建数据,但是比构建整个网格然后找到轮廓的解决方案更有效(在空间和时间上)。

ellipse

(您可以使用基础R中的library(ellipse) library(plyr) ## not necessary, but convenient m <- c(.5, -.5) sigma <- matrix(c(1,.5,.5,1), nrow=2) alpha_levels <- seq(0.5,0.95,by=0.05) ## or whatever you want names(alpha_levels) <- alpha_levels ## to get id column in result contour_data <- ldply(alpha_levels,ellipse,x=sigma, scale=c(1,1), ## needed for positional matching centre=m) lapply; rbind只是一个快捷方式)

现在情节:

plyr::ldply