14

This question is a follow-up of "How can a data ellipse be superimposed on a ggplot2 scatterplot?".

I want to create a 2D scatterplot using ggplot2 with filled superimposed confidence ellipses. Using the solution of Etienne Low-Décarie from the above mentioned post, I do get superimposed ellipses to work. The solution is based on stat_ellipse available from https://github.com/JoFrhwld/FAAV/blob/master/r/stat-ellipse.R

Q: How can I fill the inner area of the ellipse(s) with a certain color (more specifically I want to use the color of the ellipse border with some alpha)?

Here is the minimal working example modified from the above mentioned post:

# 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()

Output of working example: image of example output

Community
  • 1
  • 1
QkuCeHBH
  • 960
  • 1
  • 9
  • 23
  • did you try `stat_ellipse(alpha = 0.4)`, for example...? – Arun Feb 26 '13 at 22:03
  • Just checked - it changes the alpha of the ellipse border, but the inner area is still not filled. – QkuCeHBH Feb 26 '13 at 22:05
  • 2
    The `geom` seems to be `path` by default in `stat_ellipse` implementation. I wonder if `path` can have `fill` options... – Arun Feb 26 '13 at 22:11
  • `geom_polygon` is the `filled` version of `geom_path`... but I haven't sorted out how to make use of it yet – Justin Feb 26 '13 at 22:27
  • @lsta, the first link at the top works. The one in the code doesn't. – Arun Feb 26 '13 at 22:35

1 Answers1

20

As mentioned in the comments, polygon is needed here:

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

enter image description here

Julius Vainora
  • 47,421
  • 9
  • 90
  • 102