gpt4 book ai didi

r - 如何将观察数添加到箱线图

转载 作者:行者123 更新时间:2023-12-02 00:34:00 25 4
gpt4 key购买 nike

我正在尝试弄清楚如何向我的箱形图添加观察次数。包中的示例演示了如何在箱线图上添加观察数。但我需要在 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

最佳答案

您可以创建一个摘要 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))

关于r - 如何将观察数添加到箱线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50518046/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com