Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 draw individual ellipses but color by group

Tags:

r

ggplot2

I have data that consists of several data points for a number of individuals, and each of these individuals is from a particular study site. I'd like to plot all points, draw 95% ellipses for each individual, but then color the ellipses by study site. Unfortunately it seems that when I specify to color by site, the ellipse is drawn for the aggregated group.

The data look like this:

dat1 <- data.frame(X=rnorm(21),Y=rnorm(21),indiv_id=rep(c(1,2,3),7),group_id=rep(1,21))
dat2 <- data.frame(X=rnorm(21,5),Y=rnorm(21,5),indiv_id=rep(c(4,5,6),7),group_id=rep(2,21))
dat3 <- data.frame(X=rnorm(21,10),Y=rnorm(21,10),indiv_id=rep(c(7,8,9),7),group_id=rep(3,21))
ggdat <- rbind(dat1,dat2,dat3)
ggdat$indiv_id <- as.factor(ggdat$indiv_id)
ggdat$group_id <- as.factor(ggdat$group_id)

If I draw ellipses by individual, I can see all of the ellipses separately:

ggplot(ggdat) +
  geom_point(aes(x=X, y=Y,color=indiv_id),size=1) + # 
  stat_ellipse(aes(x=X, y=Y,color=indiv_id),type = "norm")

individual ellipses

but if I draw by the group, it makes just one ellipse per group:

ggplot(ggdat) +
  geom_point(aes(x=X, y=Y,color=indiv_id),size=1) + # 
  stat_ellipse(aes(x=X, y=Y,color=group_id),type = "norm") + #, linetype = 2
  theme(legend.position='none')

group ellipses

How can I draw all 9 ellipses but color them by group? Thanks for the help!

like image 687
Ben Carlson Avatar asked Apr 13 '16 20:04

Ben Carlson


1 Answers

Explicitly define the groups:

ggplot(ggdat) +
  geom_point(aes(x=X, y=Y,color=indiv_id),size=1) + # 
  stat_ellipse(aes(x=X, y=Y,color=group_id, group=indiv_id),type = "norm") +
  theme(legend.position='none')

enter image description here

like image 162
oshun Avatar answered Oct 06 '22 09:10

oshun