整理下转录组基因表达相关性热图
主要需要传入2个参数
函数
plot_genes_corr_tianfu <- function(exp_mat,
gene_list,
file_path = "figure/correlation_heatmap.pdf",
width = 7,
height = 7,
triangle = c("lower", "upper"),
label_type = c("stars", "pvalue")) {
library(Hmisc) # rcorr 计算相关系数和 p 值
library(reshape2) # melt 矩阵转长格式
library(ggplot2)
# 参数匹配
triangle <- match.arg(triangle)
label_type <- match.arg(label_type)
# 1. 提取指定基因表达矩阵
gene_mat <- exp_mat[gene_list, ]
# 2. 计算 Pearson 相关系数和 p 值
res <- rcorr(t(gene_mat), type = "pearson")
cor_mat <- res$r
p_mat <- res$P
# 3. 根据参数保留上三角或下三角
if (triangle == "lower") {
cor_mat[upper.tri(cor_mat)] <- NA
p_mat[upper.tri(p_mat)] <- NA
} else { # upper
cor_mat[lower.tri(cor_mat)] <- NA
p_mat[lower.tri(p_mat)] <- NA
}
# 4. 转换成长格式
cor_df <- melt(cor_mat, na.rm = TRUE)
p_df <- melt(p_mat, na.rm = TRUE)
colnames(cor_df) <- c("Gene1", "Gene2", "Correlation")
colnames(p_df) <- c("Gene1", "Gene2", "pvalue")
# 5. 合并数据
plot_df <- merge(cor_df, p_df, by = c("Gene1", "Gene2"))
# 6. 生成标签
if (label_type == "stars") {
plot_df$label <- cut(plot_df$pvalue,
breaks = c(-Inf, 0.001, 0.01, 0.05, Inf),
labels = c("***", "**", "*", ""))
} else if (label_type == "pvalue") {
plot_df$label <- formatC(plot_df$pvalue, format = "f", digits = 3)
}
# 7. 绘制热图
p <- ggplot(plot_df, aes(x = Gene1, y = Gene2, fill = Correlation)) +
geom_tile(color = "white") +
geom_text(aes(label = label), color = "black", size = 4) +
scale_fill_gradient2(low = "blue", mid = "white", high = "red", midpoint = 0,
limits = c(-1, 1), name = "Correlation") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 45, hjust = 1, size = 8),
axis.text.y = element_text(size = 8),
axis.title = element_blank(),
panel.grid = element_blank()) +
coord_fixed()
# 8. 保存 PDF
ggsave(file_path, p, width = width, height = height)
return(p)
}
调用示例
#triangle参数控制上三角还是下三角
#label_type参数控制相关性显示*号还是p值
plot_genes_corr_tianfu(exp, related_gene, file_path = "figure/upper_triangle_stars.pdf",
triangle = "upper",
label_type = "stars")
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。