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

如何基于GO术语的-log(FDR)值绘制基因型对比热图?

问题

要为rsh3和iron两个基因型的差异表达基因GO术语的-log(FDR)值绘制热图,数据框中rsh3、iron列对应各GO术语的-log(FDR)值,每行是一个GO术语。

尝试了以下代码:

library(ggplot2)

heat <- read_excel("directory/heat_final.xlsx")

heat_matrix <- as.matrix(heat)

ggplot(heat, aes(x = factor(c("rsh3", "iron")), y = GO_term)) + 
  geom_tile()

运行后报错:

> ggplot(heat, aes(x = factor(c("rsh3", "iron")), y = GO_term)) + 
+   geom_tile()
Error in `geom_tile()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 1st layer.
Caused by error in `check_aesthetics()`:
! Aesthetics must be either length 1 or the same as the data (288)
✖ Fix the following mappings: `x`
Run `rlang::last_trace()` to see where the error occurred.

目标是画出以GO术语为y轴、基因型为x轴,颜色对应-log(FDR)值的热图(类似论文图3样式)。

错误原因
  1. x = factor(c("rsh3", "iron"))仅生成2个元素的向量,但数据框有288行,ggplot要求美学映射变量的长度必须和数据行数一致,因此触发报错。
  2. 当前数据是宽格式(每个基因型对应一列),但ggplot绘制热图需要长格式数据(一列存基因型,一列存对应-log(FDR)值)。
  3. 代码未将颜色映射到-log(FDR)值,这是热图体现数值差异的核心。
修正方案

步骤1:转换数据格式

用tidyr::pivot_longer把宽格式数据转成长格式,合并基因型列。

步骤2:正确映射美学变量

x轴绑定基因型,y轴绑定GO术语,填充颜色绑定-log(FDR)值。

步骤3:优化图面样式(可选)

调整颜色渐变、主题、文字大小等,贴近目标图样式。

完整可运行代码
# 加载依赖包
library(ggplot2)
library(readxl)
library(tidyr)

# 读取数据
heat <- read_excel("directory/heat_final.xlsx")

# 宽格式转长格式
heat_long <- pivot_longer(
  data = heat,
  cols = c(rsh3, iron),  # 指定要转换的基因型列
  names_to = "genotype",  # 新列:基因型名称
  values_to = "neg_log_fdr"  # 新列:对应-log(FDR)值
)

# 绘制热图
ggplot(heat_long, aes(x = genotype, y = GO_term, fill = neg_log_fdr)) +
  geom_tile(color = "white") +  # 添加白色边框区分每个tile
  scale_fill_viridis_c(option = "plasma", name = "-log(FDR)") +  # 连续色阶调色板
  theme_minimal() +
  theme(
    axis.text.y = element_text(size = 8),  # 缩小y轴GO术语文字避免重叠
    panel.grid = element_blank(),  # 移除网格线
    legend.position = "right"
  ) +
  labs(x = "基因型", y = "GO术语")  # 自定义轴标签
额外调整建议
  • 若GO术语过多导致y轴文字重叠,可添加axis.text.y = element_text(angle = 45, hjust = 1)调整文字角度。
  • 如需按GO术语分组或-log(FDR)值排序,可先对heat_long$GO_term进行排序后再绘图。
  • 可替换调色板,比如用scale_fill_gradient2(low = "blue", mid = "white", high = "red", midpoint = median(heat_long$neg_log_fdr))生成蓝白红渐变,更符合传统热图风格。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 04:10:29