Bruno
Bruno

Reputation: 128

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

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?

Upvotes: 8

Views: 9250

Answers (3)

Alexandre Gareau
Alexandre Gareau

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

user10057935
user10057935

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

Maurits Evers
Maurits Evers

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

enter image description here


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)

enter image description here

Upvotes: 15

Related Questions