问题
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:
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