循环添加logo到ggplot2

问题描述 投票:0回答:1

我正在尝试利用此处概述的方法将徽标添加到绘图中,但在循环中。它对于一个图工作正常,但在循环中它不会按预期打印。请注意,第一个 R 徽标放置在其他任何内容之前,然后从最后一个图中删除。

我在四开本中使用它作为 html 文档发布,尽管我认为这与代码无关。

--- title: "Logo Plot Question" format: html: page-layout: full editor: source execute: echo: false warning: false editor_options: chunk_output_type: console --- ```{r} # Load ggplot2 library(ggplot2) library(grid) library(magick) # # Create data data <- data.frame( name=c("A","B","C","D","E") , value=c(25,49,36,18,45) ) logo <- magick::image_read("https://upload.wikimedia.org/wikipedia/commons/thumb/1/1b/R_logo.svg/1448px-R_logo.svg.png") for (i in 1:2){ print("Start plot") p <- ggplot(data, aes(name, value)) + geom_bar(stat = "identity", width = 1, aes(fill = value)) + coord_polar(clip = "off") + scale_y_continuous(limits = c(-10, 50)) + theme_void() + theme(legend.position = "none") + labs(title = paste0("Plot ", i)) grid::grid.raster(logo, x = 0.5, y = 0.5, just = c('center', 'top'), width = unit(0.5, 'inches')) print(p) # Does not work... # p2 <- grid::grid.raster(logo, x = 0.5, y = 0.5, # just = c('center', 'top'), # width = unit(0.5, 'inches')) # # print(p2) print("End plot") } ```
注意:我已经看到建议使用 ggsave() 保存为图像然后重新导入的解决方案。我想避免这种情况,因为我正在创建报告,并且不希望有数百个图像存在。

r loops ggplot2 r-grid
1个回答
1
投票
我喜欢将 ggplot 对象保留为 ggplot 对象。链接的文章

覆盖了现有的ggplot

在大多数情况下,我可能会使用自定义注释,但这不适用于极坐标,因此我会制作一个仅包含徽标的 ggplot,我可以使用 
中的

inset_element

函数将其添加到任何绘图中patchwork

 包装。
library(ggplot2)
library(grid)
library(magick)
library(patchwork)

data <- data.frame(
  name=c("A","B","C","D","E") ,
  value=c(25,49,36,18,45)
)

logo_plot <- ggplot() +
  theme_void() +
  annotation_custom(rasterGrob( x = 0.5, y = 0.5,
    image_read(paste0("https://upload.wikimedia.org/wikipedia/",
                      "commons/thumb/1/1b/R_logo.svg/",
                      "1448px-R_logo.svg.png")), 
    just = c('center', 'center'), width = unit(0.5, 'inches')))

for(i in 1:2) {
  
  cat("Here's plot", i, "\n")
  
  p <- ggplot(data, aes(name, value)) + 
    geom_bar(stat = "identity", width = 1,  aes(fill = value)) +
    coord_polar(clip = "off") +
    scale_y_continuous(limits = c(-10, 50)) +
    theme_void() +
    theme(legend.position = "none") +
    labs(title = paste0("Plot ", i)) +
    inset_element(logo_plot, 0, 0, 1, 1)
  
  print(p)
}

现在四开输出是:

© www.soinside.com 2019 - 2024. All rights reserved.