Having dozens of pairs of .png images to combine (and include as graphics with knitr
and LaTeX
into a PDF file), I have found that grid.arrange
leaves large margins on top and below the images. The default size of the image is 480 by 480 pixels. How can I reduce that white space?
library(png)
library(grid)
img <- readPNG(system.file("img", "Rlogo.png", package="png"))
g1 <- rasterGrob(img, interpolate=TRUE, width = .3, height=.3)
g2 <- rasterGrob(img, interpolate=TRUE,width = .6, height=.6)
grid.arrange(g1, g2, nrow=1) # displays in the RStudio plot window
dev.copy(png,'r logos.png') # creates .png file in working directory
dev.off() # inserts arranged image; 53KB; 480 x 480 pixels
Note the white space between this text and the start of the .png image.
This text marks the bottom of the .png image.
This question ggplot margin, not grid.arrange is not pertinent.
in your code, you set the size of the grobs to 30% or 60% of the viewport, so blank space is to be expected. From your problem description, you may want to use physical units such as inches or centimeters, and also set the device size to match the total size. For instance,
library(png)
library(grid)
library(gridExtra)
img <- readPNG(system.file("img", "Rlogo.png", package="png"))
g1 <- rasterGrob(img, interpolate=TRUE, width = unit(1,"in"), height=unit(1,"in"))
g2 <- rasterGrob(img, interpolate=TRUE,width = unit(2,"in"), height=unit(2,"in"))
png("fit.png",width=720,height=480,res = 480/2)
grid.arrange(g1, g2, nrow=1,widths=c(1,2))
dev.off()
produces