在ggplot2散点图中填充叠加的椭圆

时间:2013-02-26 21:57:18

标签: r ggplot2

这个问题是“How can a data ellipse be superimposed on a ggplot2 scatterplot?”的后续跟进。

我想使用带有已填充叠加置信椭圆的ggplot2创建二维散点图。使用上面提到的帖子中的Etienne Low-Décarie的解决方案,我确实得到了叠加的省略号。该解决方案基于https://github.com/JoFrhwld/FAAV/blob/master/r/stat-ellipse.R

提供的stat_ellipse

问:如何用特定颜色填充椭圆的内部区域(更具体地说,我想使用椭圆边框的颜色和某些alpha)?

以下是从上述帖子修改的最小工作示例:

# 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

1 个答案:

答案 0 :(得分:16)

如评论中所述,此处需要polygon

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

enter image description here