You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

如何在R的pheatmap中减小树状图线条宽度解决模糊问题?

解决pheatmap树状图线条模糊及宽度调整问题

嘿,我来帮你搞定这个树状图线条的问题!

首先,你单独调用gpar(lwd = 0.5)是没用的——这个函数只是生成一个绘图参数对象,但pheatmap并不会自动继承全局的绘图设置,必须把参数精准传递给树状图的绘制模块才行。

下面给你两个实用的解决方案:

方案一:用dendextend包自定义树状图线条宽度(推荐)

这个方法直观易懂,代码改动也小:

  1. 先提前生成和你原pheatmap参数一致的层次聚类结果:
library(dendextend)
# 按照原参数计算行(基因)的聚类
row_clust <- hclust(dist(assay(sce.tpm), method = "euclidean"), method = "average")
# 转换为dendrogram对象并设置线条宽度
row_dend <- as.dendrogram(row_clust)
row_dend <- set(row_dend, "branches_lwd", 0.5)
  1. 将修改好的树状图传入pheatmapclustering_tree_row参数:
pheatmap(assay(sce.tpm), 
         cellwidth = 10, cellheight= 0.009, 
         fontsize = 5, fontsize_row = 6, fontsize_col = 6, 
         scale = "row", 
         cluster_cols = FALSE, 
         clustering_tree_row = row_dend, # 使用自定义的树状图
         color = colorRampPalette(c("blue", "white", "red"))(256), 
         show_colnames = TRUE, show_rownames = FALSE)

方案二:用grid包直接修改热图对象(无需额外安装包)

如果你不想新增依赖包,可以通过grid包直接调整已生成热图的树状图:

  1. 先运行pheatmap并保存结果对象:
p <- pheatmap(assay(sce.tpm), 
              cellwidth = 10, cellheight= 0.009, 
              fontsize = 5, fontsize_row = 6, fontsize_col = 6, 
              scale = "row", 
              cluster_cols = FALSE, cluster_rows = TRUE, 
              clustering_distance_rows = "euclidean", clustering_method = "average", 
              color = colorRampPalette(c("blue", "white", "red"))(256), 
              show_colnames = TRUE, show_rownames = FALSE)
  1. 定位并修改树状图的线条宽度:
library(grid)
# 找到行树状图对应的grob对象
row_dend_idx <- which(sapply(p$gtable$grobs, function(x) x$name) == "row_dendrogram")
row_dend_grob <- p$gtable$grobs[[row_dend_idx]]
# 设置线条宽度为0.5
row_dend_grob$children[[1]]$gp$lwd <- 0.5
# 重新绘制调整后的热图
grid.newpage()
grid.draw(row_dend_grob)
grid.draw(p$gtable[-row_dend_idx])

额外优化建议:提升图像分辨率

你的输出是2×4英寸的小图,树状图模糊也可能和输出分辨率不足有关。建议保存图像时设置高dpi,比如:

png("scRNA_heatmap.png", width = 4, height = 2, units = "in", res = 300)
# 这里放入上面修改后的pheatmap代码
pheatmap(...) # 替换为你的完整代码
dev.off()

结合细线条和高分辨率,树状图的清晰度会有明显提升!

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

火山引擎 最新活动