0

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)

A lot of space gets wasted

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.

NicolasBourbaki
  • 853
  • 1
  • 6
  • 19
  • https://stackoverflow.com/questions/47721895/how-do-i-manually-fit-a-viewport-with-a-fixed-aspect-ratio-into-its-parent-such?rq=1 could at least be somehow related – NicolasBourbaki Mar 20 '18 at 13:57

1 Answers1

0

try this

ar <- dim(img)[1]/dim(img)[2]
grid.rect(vp=viewport(width=unit(0.5,"snpc"), height=unit(0.5*ar,"snpc")))
grid.raster(img, width=unit(0.5,"snpc"))

enter image description here

Marian Nasry
  • 821
  • 9
  • 22