2010-03-07 172 views
20

我有一个R函数,它为散点图产生95%的置信椭圆。输出看起来像这样,具有50点的默认为每个椭圆(50行):数据椭圆如何叠加在ggplot2散点图上?

  [,1]   [,2] 
[1,] 0.097733810 0.044957994 
[2,] 0.084433494 0.050337990 
[3,] 0.069746783 0.054891438 

我想叠加多个这样的椭圆的用于在ggplot2一个名为“网站”的因素的每一级散点图,该命令产生:

> plat1 <- ggplot(mapping=aes(shape=site, size=geom), shape=factor(site)); plat1 + geom_point(aes(x=PC1.1,y=PC2.1)) 

这是对数据集运行,称为dflat它看起来像这样:

site  geom   PC1.1  PC2.1  PC3.1  PC1.2  PC2.2 
1 Buhlen 1259.5649 -0.0387975838 -0.022889782 0.01355317 0.008705276 0.02441577 
2 Buhlen 653.6607 -0.0009398704 -0.013076251 0.02898955 -0.001345149 0.03133990 

结果是很好,但是当我尝试添加椭圆(假设这一个网站,叫“Buhlen”):

> plat1 + geom_point(aes(x=PC1.1,y=PC2.1)) + geom_path(data=subset(dflat, site="Buhlen"),mapping=aes(x=ELLI(PC1.1,PC2.1)[,1],y=ELLI(PC1.1,PC2.1)[,2])) 

我得到一个错误信息:"Error in data.frame(x = c(0.0977338099339815, 0.0844334944904515, 0.0697467834016782, : arguments imply differing number of rows: 50, 211

我已经设法在解决这一问题过去,但我不记得如何。似乎geom_path依赖于相同的点而不是绘制新的点。任何帮助,将不胜感激。

+0

你有没有尝试改变50点默认为211?它工作吗?您可能需要为您的功能添加另一个参数(点数) – 2010-03-07 17:26:42

+0

嗨,感谢您的快速回复。该功能可以改变点的数量,我用211点试了一下。它产生了一个奇怪的很厚的圆圈。我认为它不是数据的子集,首先,它应该能够用50分来绘制它 - 至少从文档中,你可以在同一个绘图上使用不同的数据集,所以自然地,不同数量的点应该是好吧。 – radu 2010-03-07 18:36:39

+0

如果你提供一个最小可重现的例子,它对我们来说会容易得多。 – xiechao 2010-03-08 13:18:39

回答

23

也许这可以帮助你:

#bootstrap 
set.seed(101) 
n <- 1000 
x <- rnorm(n, mean=2) 
y <- 1.5 + 0.4*x + rnorm(n) 
df <- data.frame(x=x, y=y, group="A") 
x <- rnorm(n, mean=2) 
y <- 1.5*x + 0.4 + rnorm(n) 
df <- rbind(df, data.frame(x=x, y=y, group="B")) 

#calculating ellipses 
library(ellipse) 
df_ell <- data.frame() 
for(g in levels(df$group)){ 
df_ell <- rbind(df_ell, cbind(as.data.frame(with(df[df$group==g,], ellipse(cor(x, y), 
             scale=c(sd(x),sd(y)), 
             centre=c(mean(x),mean(y))))),group=g)) 
} 
#drawing 
library(ggplot2) 
p <- ggplot(data=df, aes(x=x, y=y,colour=group)) + geom_point(size=1.5, alpha=.6) + 
    geom_path(data=df_ell, aes(x=x, y=y,colour=group), size=1, linetype=2) 

输出看起来是这样的:

enter image description here

Here是更为复杂的例子。

+0

如果关闭颜色,可能会出现奇怪的行为。具体而言,在绘图调用中没有'color = ...',在椭圆的边缘之间绘制一条线。这可以通过'group = group'来避免(使用不恰当的变量名称)。 – sautedman 2016-04-18 16:56:27

20

基兰Evanini,英格丽Rosenfelder和Josef Fruehwald([email protected])已经创建了一个95%的置信区间椭圆的GGPLOT2统计实现(绘制椭圆在GGPLOT2更简单的方法):

GitHub stat-ellipse.R

their site

你可以使用它作为:

library(ggplot2) 
library(devtools) 
library(digest) 
source_url("https://raw.github.com/low-decarie/FAAV/master/r/stat-ellipse.R")  
qplot(data=df, x=x, y=y, colour=colour)+stat_ellipse() 

enter image description here

要创建数据

set.seed(101) 
n <- 1000 
x <- rnorm(n, mean=2) 
y <- 1.5 + 0.4*x + rnorm(n) 
colour <- sample(c("first", "second"), size=n, replace=T) 
df <- data.frame(x=x, y=y, colour=colour) 
+0

看来ggplot2的新版本破坏了stat_ellipse,因为它逐渐弃用某些其他方法来支持S3。 – 2012-04-30 16:34:03

+3

我已经创建了一个现在在答案中找到的修复程序。 – 2012-05-04 13:30:04

+0

http://docs.ggplot2.org/dev/stat_ellipse.html – gkcn 2015-06-30 12:17:16