0
library(grid)
library(gridExtra)
library(png)
library(ggplot2)

library(RCurl)

PNG_1 <- readPNG(getURLContent("https://i.ibb.co/MVx1QsQ/A.png"))
PNG_2 <- readPNG(getURLContent("https://i.ibb.co/kHVGNfQ/B.png"))
PNG_3 <- readPNG(getURLContent("https://i.ibb.co/yVf3Hjg/C.png"))

grid <- grid.arrange(rasterGrob(PNG_1), rasterGrob(PNG_2), rasterGrob(PNG_3), ncol=3)

ggsave(grid,filename="output.png")

Output.png

Tried to set the output dimensions manually, but to no avail.

Simply wish to remove the large top and bottom margins. Thanks.

1 Answers1

0

As plots adapts to device size it's not simple to get part size. I think the easiest way is to compute aspect ratio from dimension of PNGs and provide device size to ggsave.

asp <- (ncol(PNG_1)+ncol(PNG_2)+ncol(PNG_3))/max(nrow(PNG_1),nrow(PNG_2),nrow(PNG_3))
ggsave(grid, filename= ..., width=5, height=5/asp)

to stitch those PNG you can use this code that will keep original pixel count. We can't use cbind/rbind function as readPNG returns arrays and not matrices. Fortunately the abind package provide a function to do it, abind( along=2 means cbind, along=1 for rbind)

library(abind)
PNG <- abind(PNG_1,PNG_2,PNG_3,along=2)
writePNG(PNG,"output.png")
Billy34
  • 1,777
  • 11
  • 11
  • @GrantRogers Glad to help you. Please accept my answer by clicking on the gray checkmark beside my answer. – Billy34 Mar 15 '21 at 12:29
  • Whilst the Solution works for the example rasters, my actual PNG files are larger and produce an asp value of around 2000 producing an error in ggsave command with either an out of memory error or blank file depending on adjusting the nominator (5) – Grant Rogers Mar 15 '21 at 16:47
  • I should have asked this question before but lets go now :-) What are you trying to do ? Do you need to bind several PNGs to produce another PNG ? If so using ggplot for this is maybe not the best way to do it. – Billy34 Mar 15 '21 at 18:10
  • Please disregard my last comment, I forgot to include the parenthesise in the nominator for the asp formula so all working as it should.. thanks again! To answer your question, yes it's just stitching png to produce large png. – Grant Rogers Mar 16 '21 at 10:08
  • @GrantRogers I updated my answer with a simpler code for stitching – Billy34 Mar 16 '21 at 17:46