我试图弄清楚如何向我的箱形图添加观察数量。包中的示例演示了如何在箱形图上添加观察数。但我需要在 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)
Run Code Online (Sandbox Code Playgroud)
小智 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))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7861 次 |
| 最近记录: |