在 ggplot 箱线图中重新定位 stat_summary 计数

joe*_*ey5 5 r ggplot2

df2<-data.frame(id=c("a","f","f","b","b","c","c","c","d","d","",""),
                var=c(12,20,15,18,10,30,5,8,5,5,3,5))

give.n <- function(x){
  return(c(y = mean(x), label = length(x)))
}
ggplot(data=subset(df2, id != ""), aes(x = reorder(id, -var), y = var)) +
  geom_boxplot()+
  stat_summary(fun.data = give.n, geom = "text", 
               position = position_jitter(height=1, width = 0))+
  theme(axis.text.x = element_text(angle = 90, hjust = 1, size=11, vjust = -.005))+
  ggtitle("Title")+
  xlab("")+
  ylab("value")
Run Code Online (Sandbox Code Playgroud)

我有上面的图,但是我想将计数放置在箱线图中中线上方,以便它们更明显。以这种方式使用position_jitter并不总能防止计数与中条重叠。有什么建议么?*编辑以提供 df2

Bri*_*ian 4

您需要在返回的值中定义调整y =。例如,让它返回中位数 + 0.1。您必须为您的数据手动调整 0.1。

give.n <- function(x){
  return(c(y = median(x) + 0.1, label = length(x)))
}

ggplot(iris, aes(Species, Sepal.Width)) + 
  geom_boxplot() +
  stat_summary(fun.data = give.n, geom = "text")
Run Code Online (Sandbox Code Playgroud)

或者,如果您希望它恰好位于中线和上铰链之间的中心,您可以这样计算该位置:

give.n <- function(x){
  return(c(y = mean(fivenum(x)[3:4]), label = length(x)))
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述