[英]Add a number of observations per group AND SUBGROUP in ggplot2 boxplot
[英]Add number of observations per group in ggplot2 boxplot
遵循这个问题:如何在 ggplot2 boxplot 中为每组添加多个观察值并使用组均值? ,我也想在 ggplot boxplot 中添加每组的观察数。 但是我在 aes 映射中添加了一种颜色。
现有答案显示了如何调整 y 轴中的文本位置。 如何调整 x 轴上的文本位置?
这是重现我的问题的最小示例:
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
感谢您的任何建议。
你可以只使用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
position_dodge()
的width
参数控制水平轴上的定位。 0.75 是最佳点,看看它如何适用于不同数量的分组:
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
您可以使用 geom_text 代替 stat_summary。 请参考以下问题: ggplot2 add text on top of boxplots 。
这是一个示例,说明您可以如何处理观察次数:
# Create an aggregate of median & count
> cts <- merge(aggregate(mpg ~ cyl + am, mtcars, length),
aggregate(mpg ~ cyl + am, mtcars, median),
by=c("cyl", "am"))
# Rename the col names to fit with the original dataset..
> names(cts) <- c("cyl", "am", "count", "mpg")
# As alexwhan suggested, position_dodge helps with positioning
# along the x-axis..
> ggplot(mtcars, aes(factor(cyl), mpg, colour = factor(am))) +
geom_boxplot(position = position_dodge(width=1.0)) +
geom_text(data = cts, aes(label=count),
position=position_dodge(width=1.0))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.