2013-02-26 155 views
10

此問題是「How can a data ellipse be superimposed on a ggplot2 scatterplot?」的後續操作。在ggplot2散點圖中填充疊加的橢圓

我想創建一個使用ggplot2填充疊加置信橢圓的2D散點圖。使用上述文章中的Etienne Low-Décarie的解決方案,我確實得到了疊加的橢圓。該解決方案是基於stat_ellipsehttps://github.com/JoFrhwld/FAAV/blob/master/r/stat-ellipse.R

問:我怎樣才能填補橢圓(S)與某種顏色的內部區域(更具體的我想用橢圓邊框的顏色與一些阿爾法)?

這裏是最小的工作實施例從上面提到的後修飾:

# create data 
set.seed(20130226) 
n <- 200 
x1 <- rnorm(n, mean = 2) 
y1 <- 1.5 + 0.4 * x1 + rnorm(n) 
x2 <- rnorm(n, mean = -1) 
y2 <- 3.5 - 1.2 * x2 + rnorm(n) 
class <- rep(c("A", "B"), each = n) 
df <- data.frame(x = c(x1, x2), y = c(y1, y2), colour = class) 

# get code for "stat_ellipse" 
library(devtools) 
library(ggplot2) 
source_url("https://raw.github.com/JoFrhwld/FAAV/master/r/stat-ellipse.R") 

# scatterplot with confidence ellipses (but inner ellipse areas are not filled) 
qplot(data = df, x = x, y = y, colour = class) + stat_ellipse() 

工作示例的輸出: image of example output

+0

你試過'stat_ellipse(alpha = 0.4)',例如...? – Arun 2013-02-26 22:03:57

+0

剛剛選中 - 它會更改橢圓邊框的Alpha,但內部區域仍未填充。 – QkuCeHBH 2013-02-26 22:05:44

+2

'geom'在'stat_ellipse'實現中默認情況下似乎是'path'。我想知道'path'是否可以有'fill'選項... – Arun 2013-02-26 22:11:51

回答

12

作爲評價所提到的,這裏需要polygon

qplot(data = df, x = x, y = y, colour = class) + 
    stat_ellipse(geom = "polygon", alpha = 1/2, aes(fill = class)) 

enter image description here

+0

完全按照需要工作,謝謝! – QkuCeHBH 2013-02-26 22:32:07