如何在ggplot2的箱线图中添加每组的观察数和中位数

How to add number of observation and Median per group in boxplot in ggplot2

我的问题可能是重复的,但我无法仅在 ggplot2 (tidyverse) 中完成?

我想在 ggplot2

中的每个 group/element 箱线图中添加观察次数和中位数

这是代表

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 (v2.0.0)

于 2021-06-24 创建

所有 6 个盒子的预期结果都是这样

我认为您可以使用从 article 中获取的以下解决方案。为此我们可以使用 stat_summary 函数,但对于它的 fun.data 我们必须创建一个自定义函数来计算计数和中位数。应该注意的是,我们在 stat_summary 中使用 geom_text,因此它需要 xylabel 参数。因此,当我们编写自定义 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)

我想剩下的唯一问题是标签的调整,我很快就会弄清楚。