首页 > 解决方案 > 使用 ggplot2 将显着性条添加到比例图

问题描述

我有一个比例条形图,我想添加显示组间统计差异的显着性条。我想用这个ggsignif包来创建一个类似的东西:

在此处输入图像描述

我曾尝试使用ggsignif包 and ggplot2,但结果似乎不适用于比例测试(例如 chi.square)

我的数据如下所示:

Input =("
        Group  Yes  No
        1       10       90
        2       30       70
        3       20       80
        ")

test_table = as.data.frame(read.table(textConnection(Input),
                              header=TRUE))

我最初的情节是这样的:

ggplot(test_table, 
       aes(x=Group, y=Yes)) 
    + geom_col()

标签: rggplot2

解决方案


这是一种可能性。

我们首先使用基数 R 计算成对比例之间的成对比较(校正多个假设检验)pairwise.prop.test(详见?pairwise.prop.test?prop.test):

library(broom)
library(tidyverse)
res <- pairwise.prop.test(as.matrix(test_table[, -1])) %>%
    tidy() %>%
    mutate_at(vars(contains("group")), ~factor(.x, test_table$Group))
res
## A tibble: 3 x 3
#  group1 group2 p.value
#  <fct>  <fct>    <dbl>
#1 2      1      0.00235
#2 3      1      0.149
#3 3      2      0.149

broom::tidy用来整理输出pairwise.prop.test;这不是一个严重的依赖,但可以节省我们一些时间。

Yes/(Yes + No)然后我们可以从成对测试比例测试中绘制比例和叠加 p 值

library(ggsignif)
df <- test_table %>%
    mutate(Prop = Yes / (Yes + No))

ggplot(df, aes(Group, Prop, group = Group)) +
    geom_col() +
    geom_signif(
        xmin = as.integer(res$group1),
        xmax = as.integer(res$group2),
        y_position = 0.3 + df$Prop,
        annotation = format(res$p.value, digits = 3),
        tip_length = 0.1)

在此处输入图像描述


推荐阅读