使用facet_wrap与geom_tile批量绘制Parent_Gene专属热图的问题
按Parent_Gene生成专属热图解决方案
我有1000个样本,想用facet_wrap和geom_tile生成多张热图,目标是每个Parent_Gene对应一张热图——X轴为Condition,填充色映射Response_Value,Y轴只显示该Parent_Gene下属的Gene。但当前脚本生成的每张热图会显示所有Gene,不是对应Parent_Gene的专属Gene。
数据样例
| ID | sl | condition | Gene | Response_Value | Parent_Gene |
|---|---|---|---|---|---|
| 1 | S1 | disease1 | GeneKPN1 | 2.749526 | GeneKPN |
| 2 | S2 | disease2 | GeneKPN2 | 6.606618 | GeneKPN |
| 3 | S3 | disease1 | GeneBKJH1 | 4.697644 | GeneBKJH |
当前脚本
my_data <- read.csv("my_data.csv") my_data$Parent_Gene <- gsub("([A-Z)]+)\\d+.*","\\1", my_data$Gene) library(tidyverse) gg <- ggplot(my_data, aes(x=Condition, y=Gene, fill= Response_Value))+ geom_tile(color="white", size=0.1)+ scale_fill_viridis(name="response levels") gg + coord_equal() gg + facet_wrap(~Parent_Gene, ncol=2) gg <- gg + labs(x=NULL, y=NULL, title="Comparative response levels")
问题原因与解决方法
问题出在ggplot默认会保留所有Y轴刻度(所有Gene),即使分面后某组没有对应数据。要让每个分面只显示对应Parent_Gene的Gene,只需在facet_wrap中添加scales="free_y"参数,同时配合space="free_y"让分面高度自适应Gene数量。另外原正则表达式有语法错误,也需要修正。
修改后的完整代码
my_data <- read.csv("my_data.csv") # 修正正则表达式:移除多余的右括号,确保Parent_Gene提取正确 my_data$Parent_Gene <- gsub("([A-Z]+)\\d+.*","\\1", my_data$Gene) library(tidyverse) gg <- ggplot(my_data, aes(x=Condition, y=Gene, fill= Response_Value))+ geom_tile(color="white", size=0.1)+ scale_fill_viridis(name="response levels")+ # 添加scales和space参数实现Y轴独立且自适应 facet_wrap(~Parent_Gene, ncol=2, scales="free_y", space="free_y")+ labs(x=NULL, y=NULL, title="Comparative response levels")+ coord_equal() # 输出图形 gg
关键参数说明
scales="free_y":让每个分面的Y轴独立,只显示当前分面存在数据的Genespace="free_y":根据每个分面的Gene数量自动调整高度,避免空占位- 正则修正:原表达式
([A-Z)]+)多了一个右括号,改为([A-Z]+)才能正确提取Gene前缀作为Parent_Gene
内容的提问来源于stack exchange,提问作者onedayatatime
相关产品推荐
相关产品推荐

