R 如何在ggplot背景(而不是面板)上添加图像?

R 如何在ggplot背景(而不是面板)上添加图像?,r,image,ggplot2,background,R,Image,Ggplot2,Background,如何使用图像作为ggplot2绘图的背景 例如,代码: mtcars %>% ggplot(aes(cyl)) + geom_bar() + theme(plot.background = element_rect(fill = "black")) 其结果如下: 背景颜色是黑色 如何选择图像作为背景,而不仅仅是选择其颜色?我们可以使用ggpubr::background\u image。这是一个可复制的最小示例 library(ggpubr) library(jpeg

如何使用图像作为ggplot2绘图的背景

例如,代码:

mtcars %>% 
  ggplot(aes(cyl)) + 
  geom_bar() + 
  theme(plot.background = element_rect(fill = "black"))
其结果如下:
背景颜色是黑色


如何选择图像作为背景,而不仅仅是选择其颜色?

我们可以使用
ggpubr::background\u image
。这是一个可复制的最小示例

library(ggpubr)
library(jpeg)

# Download and read sample image (readJPEG doesn't work with urls)
url <- "http://mathworld.wolfram.com/images/gifs/rabbduck.jpg"
download.file(url, destfile = "rabbduck.jpg")
img <- readJPEG("rabbduck.jpg")

ggplot(iris, aes(Species, Sepal.Length)) +
    background_image(img) +
    geom_boxplot(aes(fill = Species))

您可以将一个打印在另一个上面

library(ggplot2)
p <- ggplot(mtcars, aes(cyl)) + 
  geom_bar() +
  theme(plot.background = element_rect(fill=NA))

library(grid)
grid.draw(gList(rasterGrob(img, width = unit(1,"npc"), height = unit(1,"npc")), 
                ggplotGrob(p)))
库(ggplot2)

p不幸的是,它只在面板内绘制图像。我的疑问是,如何在面板外绘制它,就像在主题函数的plot.background参数中一样?这张图片是我所指区域的一个例子。它看起来像是
ggimage::ggbackground()
做的,尽管我还没有测试过它。@Bruno的确,Marius是正确的(非常感谢!);我做了一个编辑来展示一个例子。@Marius谢谢,我想这正是OP想要的。它甚至可以直接处理URL。我已经做了编辑。谢谢,它已经帮了很多忙了!!但是,现在图像与绘图区域背景重叠,使得数据有点难以查看和解释。您知道如何使用图像作为“整个画布”背景,但仍然允许面板背景不同(例如,我在问题中使用的图像中的浅灰色)
library(ggplot2)
p <- ggplot(mtcars, aes(cyl)) + 
  geom_bar() +
  theme(plot.background = element_rect(fill=NA))

library(grid)
grid.draw(gList(rasterGrob(img, width = unit(1,"npc"), height = unit(1,"npc")), 
                ggplotGrob(p)))