Is there a way to fit the size of the uppermost viewport (i.e. the graphics output size) to the size of the grobs inside when generating it using R's grid graphics system?
pdf(file = "test.pdf", width = 7, height = 2.7)
comes close to what I want, but I want to cut the raster image. Moreover, I want to use the graphics output directly in RMarkdown.
library(grid)
library(jpeg)
img <- readJPEG(system.file("img", "Rlogo.jpg", package="jpeg"))
grid.rect(x = 0.25, width = 0.5)
grid.raster(img, x = 0.25, width = 0.5)
grid.rect(x = 0.75, width = 0.5)
grid.raster(img, x = 0.75, width = 0.5)
I want to have the exported graphics file to be just as high as the raster image to avoid a waste of space when including the image in a text file.
An additional problem is the positioning of text on the raster images: The position of the text changes, when the image is rescaled.