Ggplot2 draw individual ellipses but color by groups

I have data that consists of several data points for several individuals, and each of these individuals is located at a specific research site. I would like to build all the points, draw 95% of the ellipses for each person, but then color the ellipses on the study site. Unfortunately, it seems that when I specify the color of the site, an ellipse is drawn for the aggregated group.

The data is as follows:

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 individually, I see all 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 in a group, it only makes one ellipse for each 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 in groups? Thanks for the help!

+7
r ggplot2
source share
1 answer

Explicitly define 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

+4
source share

All Articles