Search code examples
rggplot2ggpubrpatchwork

Error in e1 + e2 + plot_layout(ncol = 1): non-numeric argument to binary operator


I use following packages to merge the plots library(ggplot2) library(patchwork)

when try merging the plot using

(f5 | f2 | f3 | f4) / f1$gtable

It creates the output as: output

But when I change the upper figures to lower using

f1$gtable / (f5 | f2 | f3 | f4)

it throws an error as follows:

Error in e1 + e2 + plot_layout(ncol = 1): non-numeric argument to binary operator
Traceback:

1. `/.ggplot`(f1$gtable, (f5 | f2 | f3 | f4))

I tried all combinations like (f1$gtable) / (f5 | f2 | f3 | f4). But still throws the same error

reproducible data:

#crate test matrix
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 = "")
#Plot 1
f1=pheatmap(test)

#Creating group
group_df = data.frame(Groups=rep(c("Group1", "Group2"), c(5,5)))

#Plot 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")

#Plot 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")

#Plot 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")


#Plot 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")

Solution

  • It looks like ggplotify has the solution to convert the gtable to a ggplot:

    ggplotify::as.ggplot(f1$gtable) / (f5 | f2 | f3 | f4)
    

    Using idea from this question and answer