2

在添加徽标后,我希望使用该功能保存ggplot2下面的图表ggsave

# 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'))

但是,当我尝试使用 保存绘图时ggsave,它会保存不带徽标的绘图。有什么办法可以克服这个问题并使徽标出现在保存的图像中?

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

4

2 回答 2

5

或者只是使用老式的方式,首先创建一个设备

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()

你可以在 ?ggsave 中找到一小段,在没有 ggsave() 的情况下保存图像部分

于 2021-01-21T21:37:21.270 回答
3

这是一种非常笨拙的方法,即在gtable级别插入栅格,然后将 gtable 作为自定义注释重新插入。很抱歉我找不到更简洁的方法。

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)

reprex 包(v0.3.0)于 2021-01-21 创建

于 2021-01-21T21:36:52.010 回答