首页 > 解决方案 > 使用 facet wrap ggplot2 显示自定义 p 值

问题描述

我有一个多面的 ggplot 显示多个二进制变量的计数。我现在想在每个图表上显示频率计数的事后卡方比较。

以下是代表我的设计的一些(虚构)数据

condition <- c("a", "a", "a", "b", "b", "b", "c", "c", "c", "c")
binary_1 <- c(0,0,0,0,0,1,1,1,1,1)
binary_2 <- c(1,1,1,1,1,1,0,0,0,0)
binary_3 <- c(0,1,1,1,1,1,1,1,0,0)
binary_4 <- c(1,1,1,0,0,0,0,0,0,0)

df <- data.frame(condition, binary_1, binary_2, binary_3, binary_4)

我可以使用生成全局卡方检验CrossTable(df$condition, df$binary_1, chisq = TRUE, digits = 2, sresid = TRUE, expected = TRUE)

事后卡方检验是使用旧 fifer 包中的以下函数计算的

chisq.post.hoc <- function(tbl,test=c("fisher.test"), popsInRows=TRUE,control=c("fdr","BH","BY","bonferroni","holm","hochberg","hommel"),digits=4, ...) {
  #### extract correction method
  control <- match.arg(control)
  
  #### extract which test (fisher or chi square) 
  test = match.fun(test)
  
  #### test rows or columns
  if (!popsInRows) tbl <- t(tbl)
  popsNames <- rownames(tbl)
  
  #### come up with all possible comparisons
  prs <- combn(1:nrow(tbl),2)
  
  #### preallocate  
  tests <- ncol(prs)
  pvals <- numeric(tests)
  lbls <- character(tests)
  for (i in 1:tests) {
    pvals[i] <- test(tbl[prs[,i],], ...)$p.value
    lbls[i] <- paste(popsNames[prs[,i]],collapse=" vs. ")
  }
  adj.pvals <- p.adjust(pvals,method=control)
  cat("Adjusted p-values used the",control,"method.\n\n")
  data.frame(comparison=lbls,raw.p=round(pvals,digits),p.value=round(adj.pvals,digits))
}

使用此函数会产生如下表所示的输出(对于多面图中的单个变量):

matrix_1 <- as.matrix(table(df$condition, df$binary_1))

table_1 <- chisq.post.hoc(matrix_1, test='chisq.test')
table_1

事后卡方 p 值

下面是我的分面图的语法

require(tidyverse)
require(ggplot2)
require(ggsignif)
require(ggpubr)


gg_df <- df %>%
   mutate(across(starts_with("binary"), as.factor))

gg_melt <- tidyr::pivot_longer(gg_df, -condition, names_to = "binary")

ggplot(gg_melt, aes(x=condition, fill = value)) +
  geom_bar(stat="count") +
  scale_fill_manual(values = c("#FDAE61", "#9E0142"), name = "Behaviour Observed", labels = c("0" = "Absent", "1" = "Present")) +
  scale_x_discrete(labels = c(a = "Condition A", b = "Condition B", c = "Condition C")) + 
  xlab("Condition") + 
  ylab("Number of Participants") +
  theme(aspect.ratio = 1) +
  facet_wrap(~binary)

由上述语法生成的图形

我想按如下方式显示图表,其中 p 值代表上表中每个变量/方面的值。理想情况下,我还想只显示重要的比较(这是由非常少的样本组成的数据,因此不幸的是,这些事后测试都不重要)。有没有办法使用 ggsignif 做到这一点?这个线程Add P values to comparisons within groups boxplot是我找到的壁橱,但我无法应用那里给出的建议,因为函数不同,并且我的数据被转换为长格式以进行分面。

提前致谢!

在此处输入图像描述

标签: rggplot2facet-wrap

解决方案


推荐阅读