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


#1

I thought it would be fun to use ggplot2 to make a favicon for my blogdown site, but I'm having trouble using ggsave() to get the right dimensions/resolutions. Specifically, how can I save my plot while maintaining its shape and avoiding additional whitespace?

Ideally, a favicon should be saved as a 16x16 or 32x32 pixel square. My thought on the steps to this was:

However, my resulting image still has whitespace at the bottom edge. I notice that I do not get whitespace if I don't specify height, width, or dpi in my call to ggsave(). However, in this case the resulting image is not saved as a square.

I know a hack solution is just to save the plot within the IDE's plot viewer, but I'd like to get this working right. If anyone has advice/experience from a similar situation, I'd appreciate it! A reprex is below.

~

As a concrete example, here is the code I am using to create my plot.

library(ggplot2)

ggplot(
  expand.grid(x = -100:100, y = -100:100),
  aes( x = x, y = y)) +
  
  geom_tile(aes(fill = abs(x) )) +
  scale_fill_continuous(high = "cornflowerblue", low = "lightskyblue2") +
  annotate(geom = "text", label = "ER", 
x = 0, y = 0, size = 30, fontface = 6, col = "white") +
  
  # cleaning up layout
  scale_x_continuous(expand=c(0,0)) +
  scale_y_continuous(expand=c(0,0)) +
  cowplot::theme_nothing() +
  theme(aspect.ratio=1) 

The output itself appears square with no whitespace.

Here is my call to ggsave():

ggsave(filename = "./static/favicon.png",
       height = 2, width = 2, dpi = 16, plot = last_plot(), device='png'
      )

However, the resulting image clearly has whitespace:

(It's easier to see from this link against a non-white background.)


#2

Not that it answers the question, but I think there's whitespace at the bottom of the larger image as well:

Plausible but totally untested hypothesis: this could actually be the same amount (vertical height) of whitespace, which, obviously, looks bigger on the favicon:
image


#3

Wow, thanks. That actually helps a lot -- gives me a whole new direction for trouble-shooting. I'm not sure if I should feel dumber about not noticing that or the fact that I capitalized the first "G" in the subject.. :flushed:


#4

Blame auto-correct for the latter for sure! Plus, never dumb, only smarter now!