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

标签 r ggplot2 label boxplot

也许我的问题可能是重复的,但我无法在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 个盒子的预期结果都是这样的

enter image description here

最佳答案

我认为您可以使用以下来自 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)

enter image description here 我认为唯一剩下的问题是标签的调整,我试图尽快解决这个问题。

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

相关文章:

graph - 如何在graphviz点节点的TABLE标签中左对齐多行文本文字?

r - 将多边形添加到 R Shiny 传单 map

r - 如何使用 DT 包中的 renderDataTable() 格式化数据表的列?

r - 从我的数据框中创建一个虚拟变量矩阵;使用`NA`表示缺失值

R:箱线图:在重复测量的情况下在每个主题之间画线

r - 图例不会显示

c# - 在标签之间切换时执行某些操作?

android - 自定义编辑带边框的文本

R 转换 tibbles 列表的数据类型

r - 使用 data.table 生成多个 qplots