也许我的问题可能是重复的,但我无法在ggplot2
中做到这一点仅(tidyverse
)?
我想将观察数量和中位数添加到 ggplot2
中箱线图的每个组/元素中
这是代表
library(tidyverse)
set.seed(123)
df <- iris %>% sample_n(100)
df %>%
mutate(grp = ifelse(Sepal.Width > mean(Sepal.Width), 'Gr-1', 'Gr-2')) %>%
ggplot(aes(x = Species, y = Sepal.Length, fill = grp)) +
geom_boxplot() +
coord_flip() +
facet_wrap(. ~ grp)
由 reprex package 于 2021 年 6 月 24 日创建(v2.0.0)
所有 6 个盒子的预期结果都是这样的
最佳答案
我认为您可以使用以下来自 article 的解决方案。为此,我们可以使用 stat_summary 函数,但对于其 fun.data,我们必须创建一个计算计数和中位数的自定义函数。需要注意的是,我们在 stat_summary
中使用了 geom_text
,因此需要 x
或 y
和 label
参数。因此,当我们编写自定义 stat_box_sum
函数时,我们必须确保生成的数据框具有这些美观的列名称:
stat_box_sum <- function(y, upper_limit = max(iris$Sepal.Length)) {
DF <- data.frame(
y = max(y),
label = paste("N:", length(y), "\n",
"Median:", median(y), "\n")
)
DF
}
stat_box_sum(iris$Sepal.Length)
y label
1 7.9 N: 150 \n Median: 5.8 \n
df %>%
mutate(grp = ifelse(Sepal.Width > mean(Sepal.Width), 'Gr-1', 'Gr-2')) %>%
ggplot(aes(x = Species, y = Sepal.Length, fill = grp)) +
geom_boxplot() +
coord_flip() +
facet_wrap(. ~ grp) +
stat_summary(
fun.data = stat_box_sum,
geom = "text",
hjust = 0.7,
vjust = 0.7)
关于r - 如何在ggplot2的箱线图中添加每组的观察数和中位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68117425/