Ggsave aspect ratio / whitespace (use case: favicon for blogdown)

I've been having this issue for a while now. Mostly when I use coord_equal() in my plots.
The problem is the following:

  • When running ggsave(), the default ratio is whatever the pane is currently set to, as far as I understand. ("...If not supplied, uses the size of current graphics device.") But this ratio rarely works, hence the whitespace. Here is a small example:
df <- tibble(x = c(1:10),
             z = c(21:30))
ggplot(df, aes(x=x, y=1, fill=z)) + 
  geom_tile() + 
  coord_equal()
ggsave("1.png")
Saving 10.2 x 6.71 in image

  • An alternative is to supply height and width, but there is no way of knowing the ratio in advance. All I end up doing is feeding ggsave various height/weight pairs until I figure out the ratio. It takes a while sometimes, and there is gotta be a better way.

One hack I found on SO is here: r - Save plot with a given aspect ratio - Stack Overflow
But it seems like an overkill for something as simple as extracting a plot ratio and feeding it back into ggsave.

Is there a known solution to this, besides the abovementioned SO solution?

2 Likes