0
votes

I usually save the plots from ggplot2 using the the png device. The width and the height of the output are set by the arguments of the function. Blank zones are drawn when the "natural proportions" of the graph dont't suit the proportions of the device. In order to avoid this and use the whole defined canvas, the proportions of the plot must be known. ¿Is there a way to find out this value without trial and error?

This code can be used as an example:

x <- seq(from = 0, to = 1, by = 0.1)
y <- seq(from = 1, to = 2, by = 0.1)
df <- expand.grid(x = x, y = y)
df <- cbind(df, z = rnorm(ncol(df), 0, 1))

p <- ggplot(df, aes(x,y, fill = z)) + geom_raster() + coord_fixed()

ppi <- 300

#Value 0.4 is used to change inches into milimeters
png("plot.png", width = 16*0.4*ppi, height = 20*0.4*ppi, res = ppi)
print(p)
dev.off()

It can be seen that some blank space is added at the top and at the bottom to fill the png file. This could be easily corrected by using a proportion different from 20/16, which is not optimal.

1

1 Answers

0
votes

You can modify the ratio arg inside coord_fixed():

p <- ggplot(df, aes(x,y, fill = z)) + 
       geom_raster() + 
       coord_fixed(ratio = 20/16)

Alteratively you can specify the aspect.ratio inside the theme():

p <- ggplot(df, aes(x,y, fill = z)) + 
       geom_raster() + 
       theme(aspect.ratio = 20/16)

The result is the same:

enter image description here