boxplot: order groups by the mean of a subset of each group

江枫思渺然 提交于 2019-12-02 03:02:27

I don't know if this qualifies as a simple way, I personally find it simple, but I use dplyr to find the means:

#find the means for each group
library(dplyr)
means <-
df %>%
  #filter out small since you only need category equal to 'big'
  filter(category=='big') %>%
  #use the same groups as in the ggplot
  group_by(group) %>%
  #calculate the means
  summarise(mean = mean(score))

#order the groups according to the order of the means
myorder <- means$group[order(means$mean)]

In this case the order is:

> myorder
[1] a1 a2 a3

In order to arrange the order of the boxplots according to the above you just need to do:

library(ggplot2)
ggplot(df, aes(group, score)) +
  geom_boxplot() +
  #you just need to use scale_x_discrete with the limits argument
  #to pass in details of the order of appearance for the boxplots
  #in this case the order is the myorders vector
  scale_x_discrete(limits=myorder)

And that's it.

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