【问题标题】:geom_signif between boxplots of different x and same group不同x和同一组的箱线图之间的geom_signif
【发布时间】:2021-11-17 08:12:38
【问题描述】:

如何测试箱线图 x='a' 和 x='b' 之间的差异,两者都是 group='g1',然后箱线图 x='a' 和 x='b' 之间的差异都是 group=' g2'?

d = data.frame(c('a', 'a', 'a', 'a', 'b', 'b', 'b','b'),
               c(13, 12, 12, 5, 14, 6, 10, 11),
               c('g1','g2','g1','g2','g1','g2','g1','g2')) %>%
  `colnames<-`(c("x", "y", "group"))

> d
  x  y group
1 a 13    g1
2 a 12    g2
3 a 12    g1
4 a  5    g2
5 b 14    g1
6 b  6    g2
7 b 10    g1
8 b 11    g2

ggplot(d,
       aes(x, y,
           fill = group)) +
  geom_boxplot() +
  ggsignif::geom_signif(comparisons = combn(levels(factor(d$x)), 2, simplify = F))

这显示了测试“a”与“b”的结果:

但我想获得的是按组分层,如下所示:

【问题讨论】:

    标签: r dataframe ggplot2 boxplot


    【解决方案1】:

    一种方法是使用xgroup 变量之间的交互:

    library(ggplot2)
    library(dplyr)
    library(ggsignif)
    
    d %>%
      mutate(x2 = interaction(group, x)) %>%
      ggplot(aes(x2, y, fill = group)) +
      geom_boxplot() +
      geom_signif(comparisons = list(c(1, 3),
                                     c(2, 4)), 
                  y_position = rep(max(d$y), 2) * c(1, 1.05))
    

    这会更改可能不需要的 x 轴上的标签。为了使坐标轴与原始图相同,我们可以通过使用连续坐标轴并适当设置中断和标签来模拟离散坐标轴。

    d %>%
      mutate(x2 = as.integer(interaction(group, x))) %>%
      ggplot(aes(x2, y, group = x2, fill = group)) +
      geom_boxplot() +
      geom_signif(comparisons = list(c(1, 3),
                                c(2, 4)),
                  y_position = rep(max(d$y), 2) * c(1, 1.05)) +
      scale_x_continuous(breaks = c(1.5, 3.5), labels = c("a", "b"))
    

    【讨论】:

    • 谢谢,不过我得等 22 小时才能给你赏金
    猜你喜欢
    • 2016-12-06
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-08
    • 2023-01-31
    • 2021-02-28
    相关资源
    最近更新 更多