How to add an image on ggplot background (not the panel)?

家住魔仙堡 提交于 2020-06-29 05:45:12

问题


How do I use an image as the background for a ggplot2 plot?

For example, the code:

mtcars %>% 
  ggplot(aes(cyl)) + 
  geom_bar() + 
  theme(plot.background = element_rect(fill = "black"))

It results in the following: plot
and the background color is black.

How can I choose an image to be the background, and not only choose its color?


回答1:


you can plot one on top of the other,

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



回答2:


We can use ggpubr::background_image. Here is a reproducible minimal example

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


To use the whole canvas as plotting area for the background image, you can use ggimage::ggbackground (thanks @Marius)

library(ggimage)
g <- ggplot(iris, aes(Species, Sepal.Length)) +
    geom_boxplot(aes(fill = Species))
ggbackground(g, url)



来源:https://stackoverflow.com/questions/51255832/how-to-add-an-image-on-ggplot-background-not-the-panel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!