在ggplot2 boxplot中添加每个组的观察数目 [英] Add number of observations per group in ggplot2 boxplot
问题描述
以下问题:如何为每组添加多个观察值并在ggplot2 boxplot中使用组平均值?,我想要在ggplot boxplot中也添加每个组的观察数目。但是我在aes映射中添加了一个颜色。
现有的答案显示了如何调整y轴上的文本位置。如何调整x轴上的文本位置?
这是重现我的问题的最小示例:
< pre
$ b $返回(c(y = median(x)* 1.05 ,label = length(x)))
#用乘数找到完美的位置
}
p < - ggplot(mtcars,aes(factor (vs),mpg,color = factor(am)))+
geom_boxplot()+
stat_summary(fun.data = give.n,geom =text,fun.y = median)
p
感谢您的任何建议。
您可以使用位置
:
p < - ggplot(mtcars,aes(factor(vs),mpg,color = factor(am)))+
geom_boxplot( )+
stat_summary(fun.data = give.n,geom =text,fun.y = median,
position = position_dodge(width = 0.75))
p
width 参数 position_dodge()
控制水平轴上的定位。 0.75是甜蜜点,看看它如何适用于不同数量的分组:
p2 < - ggplot(mtcars,aes(因子(vs),mpg,color = factor(cyl)))+
geom_boxplot()+
stat_summary(fun.data = give.n,geom =text,fun.y = median,
position = position_dodge(width = 0.75))
p2
Following this question: How to add a number of observations per group and use group mean in ggplot2 boxplot?, I want to add number of observations per group in ggplot boxplot too. But I have added a colour into aes mapping.
The existing answer shows how to adjust text position in y axis. How could I adjust the text position in the x axis?
This is a minimum example to reproduce my problem:
library(ggplot2)
give.n <- function(x){
return(c(y = median(x)*1.05, label = length(x)))
# experiment with the multiplier to find the perfect position
}
p <- ggplot(mtcars, aes(factor(vs), mpg, colour = factor(am))) +
geom_boxplot() +
stat_summary(fun.data = give.n, geom = "text", fun.y = median)
p
Thanks for any suggestions.
解决方案 You can just use position
:
p <- ggplot(mtcars, aes(factor(vs), mpg, colour = factor(am))) +
geom_boxplot() +
stat_summary(fun.data = give.n, geom = "text", fun.y = median,
position = position_dodge(width = 0.75))
p
The width
argument of position_dodge()
controls the positioning on the horizontal axis. 0.75 is the sweet spot, see how it works for different numbers of groupings:
p2 <- ggplot(mtcars, aes(factor(vs), mpg, colour = factor(cyl))) +
geom_boxplot() +
stat_summary(fun.data = give.n, geom = "text", fun.y = median,
position = position_dodge(width = 0.75))
p2
这篇关于在ggplot2 boxplot中添加每个组的观察数目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!