2010-03-07 84 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