使用patchwork合并pheatmap与ggplot图时顺序调换触发报错求助
patchwork调换图形组合顺序触发报错的解决方案
问题描述
使用ggplot2和patchwork组合图形时,以下代码可正常生成输出:
(f5 | f2 | f3 | f4) / f1$gtable
但调换上下图形顺序后,运行以下代码会触发报错:
f1$gtable / (f5 | f2 | f3 | f4)
错误信息如下:
Error in e1 + e2 + plot_layout(ncol = 1): non-numeric argument to binary operator Traceback: 1. `/.ggplot`(f1$gtable, (f5 | f2 | f3 | f4))
尝试给两边添加括号等方式仍无法解决问题,可复现代码如下:
可复现代码
# 创建测试矩阵 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 = "") # 绘制热图 f1=pheatmap(test) # 创建分组数据 group_df = data.frame(Groups=rep(c("Group1", "Group2"), c(5,5))) # 箱线图2 int = c("Gene1", "Gene2","Gene3") df1=t(test[rownames(test) %in% int,]) df1 = as.data.frame(df1) df1$Mean = rowMeans(df1[,]) df1 = cbind(group_df, df1) f2=ggboxplot(df1, x = "Groups", y = "Mean", color = "Groups") # 箱线图3 int = c("Gene4", "Gene5","Gene6") df1=t(test[rownames(test) %in% int,]) df1 = as.data.frame(df1) df1$Mean = rowMeans(df1[,]) df1 = cbind(group_df, df1) f3=ggboxplot(df1, x = "Groups", y = "Mean", color = "Groups") # 箱线图4 int = c("Gene7", "Gene8","Gene9") df1=t(test[rownames(test) %in% int,]) df1 = as.data.frame(df1) df1$Mean = rowMeans(df1[,]) df1 = cbind(group_df, df1) f4=ggboxplot(df1, x = "Groups", y = "Mean", color = "Groups") # 箱线图5 int = c("Gene10", "Gene5","Gene1") df1=t(test[rownames(test) %in% int,]) df1 = as.data.frame(df1) df1$Mean = rowMeans(df1[,]) df1 = cbind(group_df, df1) f5=ggboxplot(df1, x = "Groups", y = "Mean", color = "Groups")
解决方案
使用patchwork的wrap_elements()函数,将f1$gtable包装为patchwork可识别的标准元素后再进行组合:
library(patchwork) wrap_elements(f1$gtable) / (f5 | f2 | f3 | f4)
原因解释
f1$gtable是pheatmap返回的gtable对象,而patchwork的/运算符默认针对ggplot对象或patchwork组合对象设计。当右侧是gtable时,patchwork可自动兼容处理;但当左侧是gtable、右侧是patchwork组合对象时,会触发/.ggplot方法的匹配错误——该方法要求左侧为ggplot/patchwork类型对象,而非gtable。通过wrap_elements()将gtable包装为patchwork标准元素后,即可正常执行上下组合逻辑。
内容的提问来源于stack exchange,提问作者user2110417
相关产品推荐
相关产品推荐

