ggplot2: boxplot with all points distributed evenly in a row

心不动则不痛 提交于 2019-12-10 04:21:12

问题


I have a boxplot generated with the following code:

b.males <- c(6, 7, 8, 8, 8, 9, 10, 10, 11, 11, 12, 12, 12, 12, 13, 14, 15)
b.females <- c(14, 13, 12, 12, 11, 10, 10, 9, 9, 9, 9, 9, 8, 8, 8, 7, 7, 7, 7)
b.total<-c(b.males,b.females)

b.m<-data.frame(b.males)
b.f<-data.frame(b.females)
b.t<-data.frame(b.total)

myList<-list(b.m, b.f, b.t)
df<-melt(myList)

colnames(df) <- c("class","count")
plt<-ggplot(df, aes(x=class,y=count))+geom_boxplot() 
plt + geom_point(aes(x = as.numeric(class) + 0, colour=class))

What I'd like to do is, for any given y-axis point, show all individual points in a row. For example, for b.males, I'd like to see 3 dots at 8, with the middle dot exactly in the center and the other two dots right next to it on either side.

I attempted:

plt + geom_point(aes(x = as.numeric(class) + 0, colour=class)) +
      geom_jitter(position=position_jitter(width=.1, height=0))

But this did not keep the points close together. Additionally, in some cases it would put multiple points to the right or left of the middle of the box, not distributing them evenly as I'd like.


回答1:


You can use geom_dotplot() to add points - with arguments binaxis="y" your values binned according to y values (counts) and argument stackdir="center" ensures that dots are centered. To change the size of points use argument dotsize=

ggplot(df,aes(class,count))+geom_boxplot()+
  geom_dotplot(aes(fill=class),binaxis="y",stackdir="center",dotsize=0.5)



来源:https://stackoverflow.com/questions/20547309/ggplot2-boxplot-with-all-points-distributed-evenly-in-a-row

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!