如何将观测数量添加到箱线图中

3

我正在尝试找出如何在我的箱线图中添加观察数量。该软件包中的示例演示了如何在箱线图上添加观察数量,但我需要将观察数量写在x轴上。我将基于此创建一个可重现的示例。

# function for number of observations 
give.n <- function(x){
 return(c(y = median(x)*1.05, label = length(x))) 
# experiment with the multiplier to find the perfect position
}


# plot
ggplot(mtcars, aes(factor(cyl), mpg, label=rownames(mtcars))) +
 geom_boxplot(fill = "grey80", colour = "#3366FF") +
 stat_summary(fun.data = give.n, geom = "text", fun.y = median) 

enter image description here

1个回答

8
你可以创建一个汇总的data.frame,并将其作为数据参数传递给geom_text图层。
library(dplyr)
df <- count(mtcars, cyl)

# plot
ggplot(mtcars, aes(factor(cyl), mpg, label=rownames(mtcars))) +
  geom_boxplot(fill = "grey80", colour = "#3366FF") +
  geom_text(data = df, aes(y = 0, label = n))

1
谢谢你,Imran。那很有帮助。 - SNEHA

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接