Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

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

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)

question from:https://stackoverflow.com/questions/65835871/how-to-save-ggplot-with-an-added-logo-to-it-while-preserving-image-quality

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...