首页 > 解决方案 > R ggpubr Boxplot 将摘要统计标签添加到动态 Y 轴

问题描述

我想在动态 y 轴的最大值处的箱形图上添加汇总统计信息。

在实际数据中,y 轴是一个动态下拉列表,其中一个值介于 0 - 6 之间;另一个在 0 - 100 之间。在下面的示例中,我已经硬编码了我希望标签所在的位置,但我无法在真实数据中对它们进行硬编码。

有没有办法:

在 y 轴上方的图形之外设置标签?这样即使轴发生变化,标签也不会移动?

或者有没有办法将它设置为 Y + n 的最大值?

例子:

# library
library(ggplot2)
library(ggpubr)

# create a data frame
variety=rep(LETTERS[1:7], each=40)
treatment=rep(c("high","low"),each=20)
note=seq(1:280)+sample(1:150, 280, replace=T)
data=data.frame(variety, treatment ,  note)

# grouped boxplot
ggplot(data, aes(x = variety, y = note, fill = treatment)) +
  geom_boxplot() +
  scale_fill_manual(values = c("#79AAB9", "#467786")) +
  stat_compare_means(aes(group = treatment), label = "p.format") +
  stat_summary(
    fun.data = function(x)
      data.frame(y = 460, label = paste(round(median(
        x
      ), 1))),
    geom = "text",
    aes(group = treatment),
    hjust = 0.5,
    position = position_dodge(0.9)
  ) +
  stat_summary(
    fun.data = function(x)
      data.frame(y = 445, label = paste("n", length(x))),
    geom = "text",
    aes(group = treatment),
    hjust = 0.5,
    position = position_dodge(0.9)
  ) +
  expand_limits(y = 100)

箱线图示例

非常感谢您提前提供的任何帮助。

标签: rggplot2labelboxplotggpubr

解决方案


设法通过@MarkNeal 的建议得到以下工作

# library
library(ggplot2)
library(ggpubr)

# create a data frame
variety=rep(LETTERS[1:7], each=40)
treatment=rep(c("high","low"),each=20)
note=seq(1:280)+sample(1:150, 280, replace=T)
data=data.frame(variety, treatment ,  note)

# grouped boxplot
ggplot(data, aes(x = variety, y = note, fill = treatment)) +
  geom_boxplot() +
  scale_fill_manual(values = c("#79AAB9", "#467786")) +
  stat_compare_means(aes(group = treatment), label = "p.format", vjust = 3) +
  stat_summary(
    fun.data = function(x)
      data.frame(y= Inf, label = paste(round(median(
        x
      ), 1))),
    geom = "text",
    aes(group = treatment),
    hjust = 0.5, vjust = 1,
    position = position_dodge(0.9)
  ) +
  stat_summary(
    fun.data = function(x)
      data.frame(y = Inf, label = paste("n", length(x))),
    geom = "text",
    aes(group = treatment),
    hjust = 0.5, vjust = 2,
    position = position_dodge(0.9)
  )

在此处输入图像描述


推荐阅读