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:
- make a plot that looks good square
theme(aspect.ratio = 1)or
coord_fixed()to ensure plot stays square
height = 2, width = 2, dpi = 16to get a 32x32 pixel image (based on the relationship between height, width, dpi, and pixels )
However, my resulting image still has whitespace at the bottom edge. I notice that I do not get whitespace if I don't specify
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(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.)