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

如何用ggplot2绘制上下三角分别展示Fst值与P值的热图

解决方案

核心思路

通过条件判断区分上下三角区域,在同一ggplot图层中分别绘制左下三角的Fst色块、标注Fst值,以及右上三角的P值标注,避免拼接两个图的不规范操作。

步骤1:预处理数据

确保种群列按指定顺序转为因子,同时补全上下三角及对角线数据(如果你的原始数据只有左下三角):

library(tidyverse)

# 指定坐标轴固定顺序
pop_order <- c("MSI", "WB", "JI", "QC")

# 如果你只有左下三角数据,补全右上三角的P值数据
# 假设你的lowerTri数据包含pop1、pop2、fst、p_value列
upper_tri_df <- pairwise_fst_maxmeanDP_df_lowerTri %>%
  select(pop1 = pop2, pop2 = pop1, p_value) %>%
  mutate(fst = NA)

# 合并上下三角+对角线数据
full_df <- bind_rows(
  pairwise_fst_maxmeanDP_df_lowerTri,
  upper_tri_df,
  tibble(pop1 = pop_order, pop2 = pop_order, fst = NA, p_value = NA) # 对角线
) %>%
  mutate(
    pop1 = factor(pop1, levels = pop_order),
    pop2 = factor(pop2, levels = pop_order)
  )

步骤2:绘制三角热图

用ggplot2一次性完成所有元素的绘制:

library(ggplot2)

ggplot(full_df, aes(x = pop1, y = pop2)) +
  # 左下三角:绘制Fst着色块
  geom_tile(
    aes(fill = ifelse(as.numeric(pop2) > as.numeric(pop1), fst, NA)),
    color = "white", # 色块间的白色分隔线
    size = 0.5
  ) +
  # 设置Fst的颜色渐变(0-1范围)
  scale_fill_gradient(
    low = "#f7fbff",
    high = "#08306b",
    name = "Pairwise-Fst",
    limits = c(0, 1),
    na.value = "transparent" # 右上三角透明
  ) +
  # 左下三角:标注Fst值(保留3位小数)
  geom_text(
    aes(label = ifelse(as.numeric(pop2) > as.numeric(pop1), sprintf("%.3f", fst), "")),
    size = 3.5
  ) +
  # 右上三角:标注P值(科学计数法,保留2位小数)
  geom_text(
    aes(label = ifelse(as.numeric(pop2) < as.numeric(pop1), sprintf("%.2e", p_value), "")),
    size = 3.5
  ) +
  # 对角线:标注种群名称
  geom_text(
    aes(label = ifelse(pop1 == pop2, pop1, "")),
    size = 4.5,
    fontface = "bold"
  ) +
  # 反转Y轴,让左下三角位于图表左下角
  scale_y_discrete(limits = rev(pop_order)) +
  # 调整主题样式
  labs(x = "", y = "") +
  theme_minimal() +
  theme(
    panel.grid = element_blank(),
    axis.text = element_text(size = 11),
    legend.title = element_text(size = 12),
    legend.text = element_text(size = 10)
  )

关键细节说明

  • as.numeric(pop2) > as.numeric(pop1):利用因子的数值化结果判断左下三角区域(配合Y轴反转实现位置对应)
  • na.value = "transparent":让右上三角无填充色,只显示P值标注
  • 统一用sprintf格式化数值,保证标注格式一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 02:18:30