让我们考虑一下这个数据:
df = data.frame('score'=round(runif(15, 1, 10)),
'group'=paste0("a",rep(c(1,2,3),each=5)),
'category'=rep(c("big", "big", "big", "big", "small"), 3))
我想用以下方法绘制这些数据的箱线图ggplot2
。我想要的是:箱线图(分数〜组),但箱线图根据每组“大”个体的平均值排列。
如果不创建新变量,我无法以简单的方式弄清楚这一点。可以使用 Dplyr。谢谢。
我不知道这是否是一种简单的方法,我个人觉得它很简单,但我使用dplyr
找到方法:
#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)]
在这种情况下,顺序是:
> myorder
[1] a1 a2 a3
为了根据上面的内容排列箱线图的顺序,您只需要执行以下操作:
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)
就是这样。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)