Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill superimposed ellipses in ggplot2 scatterplots

Tags:

r

ggplot2

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

like image 808
QkuCeHBH Avatar asked Feb 26 '13 21:02

QkuCeHBH


1 Answers

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

like image 133
Julius Vainora Avatar answered Oct 09 '22 20:10

Julius Vainora