ggplot: arranging boxplots of multiple y-variables for each group of a continuous x

我与影子孤独终老i 提交于 2019-11-28 04:35:17

Not exactly sure what you're looking for. Is this close?

library(ggplot2)
library(plyr)
ggplot(dfmelt, aes(x=factor(round_any(x,0.5)), y=value,fill=variable))+
  geom_boxplot()+
  facet_grid(.~variable)+
  labs(x="X (binned)")+
  theme(axis.text.x=element_text(angle=-90, vjust=0.4,hjust=1))

EDIT (response to OP's comment)

You can put the Y's next to each other in each bin by just taking out the facet_grid(...) call, but I don't recommend it.

ggplot(dfmelt, aes(x=factor(round_any(x,0.5)), y=value, fill=variable))+
  geom_boxplot()+
  labs(x="X (binned)")+
  theme(axis.text.x=element_text(angle=-90, vjust=0.4,hjust=1))

If you have to do it this way, it's still clearer using facets:

dfmelt$bin <- factor(round_any(dfmelt$x,0.5))
ggplot(dfmelt, aes(x=bin, y=value, fill=variable))+
  geom_boxplot()+
  facet_grid(.~bin, scales="free")+
  labs(x="X (binned)")+
  theme(axis.text.x=element_blank())

Note the addition of a bin column to dfmelt. This is because using factor(round_any(x,0.5)) in the facet_grid(...) formula doesn't work.

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