Reputation: 128
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?
Upvotes: 8
Views: 9250
Reputation: 91
I think I had a similar issue than OP - in regard to the background image being to intense and making the data less readable. I added a annotate("rect") with alpha parameter to tone down the background image.
library(ggpubr)
image <- png::readPNG("image.png")
df %>%
ggplot(aes(x,y)) +
background_image(image) +
annotate("rect",
xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf,
fill = "white", alpha = .5) +
...
Upvotes: 1
Reputation: 46
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)))
Upvotes: 3
Reputation: 50668
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)
Upvotes: 15