本文介绍了用ggplot2绘制多元高斯轮廓的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用均值和协方差已知的2D高斯分布轮廓绘制图.理想情况下,我只需要指定函数,它就会以2D形式绘制(如stat_function,除了2维).我可以通过生成概率网格使用geom_raster来做到这一点.我可以改用geom_contour2d吗?

I'm trying to augment a plot with contours from a 2D Gaussian distribution with known mean and covariance. Ideally I would just have to specify the function and it would be plotted in 2D (like stat_function except for 2 dimensions). I can do it with geom_raster by generating a grid of probabilites. Can I use geom_contour2d somehow instead?

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)

推荐答案

我将使用ellipse包直接构造轮廓数据.这仍然需要一个单独的调用来构造数据,但是比构造整个网格然后找到轮廓的解决方案要有效得多(在空间和时间上).

I would use the ellipse package to construct the contour data directly. This still requires a separate call to construct the data, but is much more efficient (in both space and time) than your solution of constructing an entire grid and then finding the contours.

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)

(您可以在R的基础上使用lapplyrbindplyr::ldply只是一个快捷方式)

(you could use lapply and rbind from base R; plyr::ldply is just a shortcut)

现在的情节:

library(ggplot2)
ggplot(contour_data,aes(x,y,group=.id))+geom_path()

这篇关于用ggplot2绘制多元高斯轮廓的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 20:41