How to save ggplot with an added logo to it while preserving image quality

Viewed 179

I am looking to save this ggplot2 chart below using the ggsave function after I've added a logo to it

# Load packages and dataset
library(ggplot2)
library(magick)

data(mpg, package="ggplot2")

# Load a logo from Github

logo <- image_read("https://jeroen.github.io/images/frink.png")

# Plot Code

ggplot(mpg, aes(cty, hwy)) +
  geom_count(col="tomato3", show.legend=F)

# Add logo to plot

grid::grid.raster(logo, x = 0.04, y = 0.03, just = c('left', 'bottom'), width = unit(1, 'inches'))

However, when I try to save the plot using ggsave, it saves the plot without the logo. Any way to overcome this and have the logo appear in the saved image?

ggsave('Plot.tiff',width =10,height = 6, device = 'tiff', dpi = 700)

2 Answers

Or just use the old fashioned way, by creating a device first

png()
ggplot(mpg, aes(cty, hwy)) +
  geom_count(col="tomato3", show.legend=F)
grid::grid.raster(logo, x = 0.04, y = 0.03, just = c('left', 'bottom'), width = unit(1, 'inches'))
dev.off()

you can find a small paragraph in ?ggsave, section Saving images without ggsave()

Here is an incredibly clunky way by inserting the raster at the gtable level and then re-inserting the gtable as a custom annotation. I'm sorry I couldn't find a more succinct way.

library(ggplot2)
library(magick)
#> Linking to ImageMagick 6.9.11.57
#> Enabled features: cairo, freetype, fftw, ghostscript, heic, lcms, pango, raw, rsvg, webp
#> Disabled features: fontconfig, x11

data(mpg, package="ggplot2")

# Load a logo from Github

logo <- image_read("https://jeroen.github.io/images/frink.png")

# Plot Code

g <- ggplot(mpg, aes(cty, hwy)) +
  geom_count(col="tomato3", show.legend=F)
# Convert to gtable
g <- ggplotGrob(g)

# Save logo as grob
grob <- grid::rasterGrob(logo, x = 0.04, y = 0.03, just = c('left', 'bottom'), 
                         width = unit(1, 'inches'))


# Insert grob in gtable
g <- gtable::gtable_add_grob(
  g, grob, t = 1, l = 1, b = dim(g)[1], r = dim(g)[2]
)

# Add old plot as annotation to new plot with void theme
ggplot() +
  annotation_custom(g) +
  theme_void()

ggsave('Plot.tiff',width =10,height = 6, device = 'tiff', dpi = 700)

Created on 2021-01-21 by the reprex package (v0.3.0)

Related