【发布时间】:2020-10-12 10:49:52
【问题描述】:
问题:
我想使用 PNG 或 JPEG 图像制作多面板图。这些图像不是在 R 中创建的,但我想在 R 中将它们拼凑在一起以形成一个图形。所有图像的大小/尺寸都相同。
我的尝试:
library(png)
img1 <- readPNG("filepath/img1.png")
img2 <- readPNG("filepath/img2.png")
library(patchwork)
patch <- img1 + img2
patch
当我运行它时,我收到以下错误:
[ reached getOption("max.print") -- omitted 3 matrix slice(s) ]
我多次增加了最大打印数量(达到了高得离谱的数字):
options(maxprint = 1000000000000)
但仍然得到同样的错误。
然后我尝试使用以下方法将每个图像制作成 ggplot(没有点):
library(ggplot2)
img1plot <- ggplot() +
background_image(img1) +
theme(plot.margin = margin(t=1, l=1, r=1, b=1, unit = "cm"))
返回以下错误:
Error in background_image(d311) :
could not find function "background_image"
有没有另一种方法可以在 R 中将图像拼凑在一起来制作图形?
编辑:
根据@davidnortes 的评论,我尝试了以下方法:
p1 <- ggplot2::annotation_custom(grid::rasterGrob(img1,
width=ggplot2::unit(1,"npc"),
height=ggplot2::unit(1,"npc")),
-Inf, Inf, -Inf, Inf)
p2 <- ggplot2::annotation_custom(grid::rasterGrob(img2,
width=ggplot2::unit(1,"npc"),
height=ggplot2::unit(1,"npc")),
-Inf, Inf, -Inf, Inf)
library(cowplot)
plots <- plot_grid(
p1, p2,
labels = c('A', 'B'),
align="hv"
)
plots
我收到以下警告消息,但情节没有形成:
Warning messages:
1: In as_grob.default(plot) :
Cannot convert object of class LayerInstanceLayerggprotogg into a grob.
2: In as_grob.default(plot) :
Cannot convert object of class LayerInstanceLayerggprotogg into a grob.
【问题讨论】:
-
对不起,伙计!我对 ggplot2 的回答中有一个错误;这就是你得到错误的原因。我正在编辑它
-
你的第一次尝试几乎成功了,顺便说一句。使用
library(patchwork),您可以使用patch <- wrap_elements(img1) + wrap_elements(img2)。您不能直接查看它,但ggsave可以正常工作。另外,请确保在readPNG中设置native = TRUE。 -
感谢您添加此@mths!