能否用patchwork组合ggMarginal图?报错问题求解
问题:用patchwork组合ggExtra生成的带边际直方图的图形时报错
在R中用ggplot2绘制散点图,通过ggExtra包的ggMarginal函数为其添加X轴直方图。尝试用patchwork包组合这些带边际直方图的图形时,出现「non-numeric argument to binary operator」错误。仅用patchwork组合普通ggplot图形可正常运行,请问是否有简便方法组合这类带边际直方图的图?还是必须单独绘制散点图和直方图,再用patchwork组合?
复现代码
library(ggplot2) library(ggExtra) library(patchwork) # 补充创建数据框(原代码缺失部分) col_pH <- runif(n = 100, min = 5, max = 8) col_abund <- runif(n=100, min = 0, max = 5.5) col_SOC <- runif(n=100, min = 0.5, max = 3.6) testdata <- data.frame(col_pH, col_abund, col_SOC) testplot1 <- ggplot(testdata, aes(x=col_pH, y=col_abund))+ geom_point()+ theme(legend.position = "none") margin_testplot1 <- ggMarginal(testplot1, type = "histogram", bins = 16, margins = "x") testplot2 <- ggplot(testdata, aes(x=col_SOC, y=col_abund))+ geom_point()+ theme(legend.position = "none") margin_testplot2 <- ggMarginal(testplot2, type = "histogram", bins = 16, margins = "x") testplot1/testplot2 # 正常运行 X <- testplot1/testplot2 X|testplot1 # 正常运行 margin_testplot1/margin_testplot2 # 报错:non-numeric argument to binary operator
原因
ggMarginal返回的不是标准的ggplot对象,而是gtable类型的图形表格对象(来自grid包),而patchwork的核心运算符(/、|等)仅支持原生ggplot对象,直接组合自然会触发类型不匹配的错误。
解决方法
不需要单独拆分绘制散点图和直方图,有两种简便方案:
方案1:用gridExtra包组合gtable对象
gridExtra的grid.arrange()函数原生支持gtable对象的排列,可直接指定行列数:
library(gridExtra) # 纵向排列两个带边际直方图的图 grid.arrange(margin_testplot1, margin_testplot2, nrow = 2) # 横向排列两个图 grid.arrange(margin_testplot1, margin_testplot2, ncol = 2)
方案2:用wrap_elements()转成patchwork兼容对象
patchwork提供了wrap_elements()函数,可以将非ggplot的图形对象(比如gtable)包装成patchwork能识别的元素,之后就能继续用patchwork的语法自由组合:
# 包装gtable对象 p1 <- wrap_elements(margin_testplot1) p2 <- wrap_elements(margin_testplot2) # 纵向排列(和patchwork原语法一致) p1 / p2 # 横向排列 p1 | p2 # 甚至可以和普通ggplot对象混合组合 p1 | testplot1
内容的提问来源于stack exchange,提问作者Wiredwolf
相关产品推荐
相关产品推荐

