在 ggplot2 boxplot 中为每个组和子组添加一些观察值
Add a number of observations per group AND SUBGROUP in ggplot2 boxplot
这看起来像是 this question 的重复,但实际上我想扩展原始问题。
我想在 ggplot 中用每组和子组的观察数量来注释箱线图。按照示例或原始 post,这是我的最小示例:
require(ggplot2)
give.n <- function(x){
return(c(y = median(x)*1.05, label = length(x)))
# experiment with the multiplier to find the perfect position
}
ggplot(mtcars, aes(factor(cyl), mpg, fill = factor(gear))) +
geom_boxplot() +
stat_summary(fun.data = give.n, geom = "text", fun.y = median)
我的问题是样本数量全部排在组的中心,而不是绘制在适当的箱线图上(如下图所示):
是你想要的吗?
require(ggplot2)
give.n <- function(x){
return(c(y = median(x)*1.05, label = length(x)))
# experiment with the multiplier to find the perfect position
}
ggplot(mtcars, aes(factor(cyl), mpg, fill = factor(gear))) +
geom_boxplot() +
stat_summary(fun.data = give.n, geom = "text", fun.y = median, position=position_dodge(width=0.75))
这看起来像是 this question 的重复,但实际上我想扩展原始问题。
我想在 ggplot 中用每组和子组的观察数量来注释箱线图。按照示例或原始 post,这是我的最小示例:
require(ggplot2)
give.n <- function(x){
return(c(y = median(x)*1.05, label = length(x)))
# experiment with the multiplier to find the perfect position
}
ggplot(mtcars, aes(factor(cyl), mpg, fill = factor(gear))) +
geom_boxplot() +
stat_summary(fun.data = give.n, geom = "text", fun.y = median)
我的问题是样本数量全部排在组的中心,而不是绘制在适当的箱线图上(如下图所示):
是你想要的吗?
require(ggplot2)
give.n <- function(x){
return(c(y = median(x)*1.05, label = length(x)))
# experiment with the multiplier to find the perfect position
}
ggplot(mtcars, aes(factor(cyl), mpg, fill = factor(gear))) +
geom_boxplot() +
stat_summary(fun.data = give.n, geom = "text", fun.y = median, position=position_dodge(width=0.75))