使用ggarrange合并热图与PCA 3D图失败,仅显示热图求助
问题原因
ggarrange仅支持ggplot2对象或gtable对象拼接,但plot(res.hcpc, choice = "3D.map")生成的是Base R绘图系统的图像,这类对象无法直接被ggarrange识别,因此拼接时仅显示兼容的热图,PCA图被忽略。
解决方案:将Base R图转为ggplot兼容格式
通过ggplotify包将Base R绘图转换为ggplot对象,即可正常用ggarrange拼接。
完整修正代码
library(factoextra) library(FactoMineR) library(pheatmap) library(RColorBrewer) library(ggpubr) library(ggplotify) # 新增转换工具包 # 生成测试矩阵 test = matrix(rnorm(200), 20, 10) test[1:10, seq(1, 10, 2)] = test[1:10, seq(1, 10, 2)] + 3 test[11:20, seq(2, 10, 2)] = test[11:20, seq(2, 10, 2)] + 2 test[15:20, seq(2, 10, 2)] = test[15:20, seq(2, 10, 2)] + 4 colnames(test) = paste("Test", 1:10, sep = "") rownames(test) = paste("Gene", 1:20, sep = "") # 定义行注释 annotation_row = data.frame(GeneClass = factor(rep(c("Path1", "Path2", "Path3"), c(10, 4, 6))), AdditionalAnnotation = c(rep("random1", 10), rep("random2", 10))) rownames(annotation_row) = paste("Gene", 1:20, sep = "") # 绘制热图并保存gtable对象 a <- pheatmap(test, annotation_row = annotation_row) # 计算PCA和HCPC res.pca <- PCA(test, ncp = 3, graph = FALSE) res.hcpc <- HCPC(res.pca, graph = FALSE) # 将3D PCA图转为ggplot对象 b <- as.ggplot(function() plot(res.hcpc, choice = "3D.map")) # 合并两张图 ggarrange(a$gtable, b, labels = c("A", "B"), ncol = 2)
关键修改点
- 新增
library(ggplotify)加载格式转换工具 - 用
as.ggplot(function() plot(...))将Base R绘图包裹为ggplot对象,使ggarrange能识别 - 后续拼接逻辑保持不变即可正常显示两张图
内容的提问来源于stack exchange,提问作者user2110417
相关产品推荐
相关产品推荐

