You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中将dunnTest成对比较结果转换为矩阵并绘制p值热图

解决方案

你需要先拆分成对比较列生成对称矩阵,再基于ggplot绘制热图,完整可运行代码如下:

步骤1:加载依赖包&准备数据

# 加载需要的包
library(tidyverse)

# 你的示例数据
sorted <- 
    tibble::tribble(
      ~Comparison, ~Z, ~P.adj,
      "A1 - B1",    0.225445,     0.854086,
      "A1 - B2",    0.45513,     0.000235,
      "A1- B3",    0.32555,     0.221551,
       "B1 - B2",   0.44544,       0.0000552,
       "B2 - B3",    0.22511,      0.0000112)

步骤2:拆分比较列,生成对称方阵数据

# 拆分Comparison列为两个分组列,自动处理横杠前后的空格问题
pair_data <- sorted %>%
  separate(Comparison, into = c("group1", "group2"), sep = "\\s*-\\s*") %>%
  select(group1, group2, P.adj)

# 补全对称行(因为A-B和B-A的p值一致),同时添加对角线(同一组比较p值设为1)
full_pair <- bind_rows(
  pair_data,
  pair_data %>% rename(group1 = group2, group2 = group1),
  tibble(group1 = unique(c(pair_data$group1, pair_data$group2)),
         group2 = unique(c(pair_data$group1, pair_data$group2)),
         P.adj = 1)
)

# 可选:添加显著性标记
full_pair <- full_pair %>%
  mutate(sig = case_when(
    P.adj < 0.001 ~ "***",
    P.adj < 0.01 ~ "**",
    P.adj < 0.05 ~ "*",
    TRUE ~ "ns"
  ))

步骤3:绘制p值热图

ggplot(full_pair, aes(x = group1, y = group2, fill = P.adj)) +
  geom_tile(color = "white") +
  # 瓷砖上显示p值和显著性标记,可根据需要调整显示内容
  geom_text(aes(label = paste0(round(P.adj, 5), "\n", sig)), color = "black", size = 3.5) +
  # 调整颜色渐变,可根据偏好修改,log10转换适合p值差异较大的场景
  scale_fill_gradient(low = "#ff6b6b", high = "#f7fff7", trans = "log10") +
  # 调整坐标轴和主题
  labs(x = NULL, y = NULL, fill = "校正后p值") +
  theme_minimal() +
  theme(axis.text = element_text(size = 12),
        legend.position = "bottom")

如果不需要显示瓷砖内的文本,去掉geom_text层即可,也可以根据需求修改颜色映射、分组排序等参数。

内容的提问来源于stack exchange,提问作者Tyler Ruddenfort

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 23:51:00