r - 使用 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
下面是我的分面图的语法
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是我找到的壁橱,但我无法应用那里给出的建议,因为函数不同,并且我的数据被转换为长格式以进行分面。
提前致谢!
解决方案
推荐阅读
- azure - 使用 .json 脚本自动化 CI/CD
- python - 关闭多处理记录器处理程序
- mongodb - $rename - 重命名嵌入文档中的字段
- python-3.x - how to read gml file with label in jupyter notebook?
- python - 导入bloomberg Api 时出错,如何解决?
- algorithm - 如何提高掺杂矩阵构建算法的速度
- c# - PdfBox 图像提取:该库从文档中为每一页提取所有图像
- node.js - Laravel-Echo + Passport 认证 + Node JS 客户端
- php - 无法在服务器上上传文件 - 错误是警告:POST Content-Length of 42669632 bytes exceeded
- cuda - WMMA 默认内核