Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
513 views
in Technique[技术] by (71.8m points)

r - ggplot2 draw individual ellipses but color by group

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...