当使用填充美学(或在x轴处避开样品)时,我无法在箱线图附近添加标签(本例中的样本大小)。
它适用于最常用的数据集(mtcars)和示例
library(ggplot2)
fun_length <- function(x){
return(data.frame(y=median(x),label= paste0("n=", length(x))))
}
ggplot(mtcars, aes(factor(cyl), mpg)) +
geom_boxplot() +
stat_summary(aes(x = factor(cyl)),
fun.data = fun_length, geom = "text",
vjust = +1, size = 4)
library(plyr)
ddply(mtcars, .(cyl), summarise, label = length(mpg))
cyl label
1 4 11
2 6 7
3 8 14
但是我无法为此版本添加相同的标签,现在显示每个vs级别的样本大小。
ggplot(mtcars, aes(factor(cyl), mpg)) +
geom_boxplot(aes(fill = factor(vs))) +
stat_summary(aes(x=factor(cyl)),
fun.data = fun_length, geom = "text")
ddply(mtcars, .(cyl, vs), summarise, label = length(mpg))
cyl vs label
1 4 0 1
2 4 1 10
3 6 0 3
4 6 1 4
5 8 0 14
欢迎任何帮助。提前谢谢。
答案 0 :(得分:3)
ggplot(mtcars, aes(factor(cyl), mpg)) +
geom_boxplot(aes(fill = factor(vs)), position=position_dodge(.9)) +
stat_summary(aes(x=factor(cyl), fill = factor(vs)), position=position_dodge(.9),
fun.data = fun_length, geom = "text",
vjust = +1, size = 4)
答案 1 :(得分:2)
这应该有效 - 将vs
移至ggplot调用,然后您不需要aes
中的stat_summary
并添加position_dodge
(演示文稿)
ggplot(mtcars, aes(factor(cyl), mpg, fill = factor(vs))) +
geom_boxplot(position=position_dodge(width=0.9)) +
stat_summary( fun.data = fun_length, geom = "text",
position=position_dodge(width=0.9), vjust=2)