Add a background png image to ggplot2

[This article was first published on julianhi's Blog » R Tutorials, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Hey everybody,

this is just a short post but I found it very useful. I want to show you how to add images as a background to your ggplot2 plots.

To do so we need the packages png and grid


packs <- c("png","grid")
lapply(packs, require, character.only = TRUE)

Btw, this is just a cool and fast way to import different packages at once.

As an example for a background image plot I used the Sochi Olympic Medals plot by TRinker, which looks really good.

The tutorial shows you how to create a plot based on the current medals scores which looks like this:

sochi olympic games viz

Add an image

First of all we need to load the picture. Just place it in your working directory and load it with:


img <- readPNG("sochi-logo.png")

And add a raster:


g <- rasterGrob(img, interpolate=TRUE)

And that´s nearly all!

Now we just have to add it with the annotation_custom() function to our plot.


plot1 <- ggplot(mdat, aes(x = Count, y = Country, colour = Place))

+ geom_point()

+ facet_grid(.~Place) + theme_bw()

+ annotation_custom(g, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf)

+ scale_colour_manual(values=c("#CC6600", "#999999", "#FFCC33", "#000000"))

The result will look like this:

sochi rstats image png gglot2


To leave a comment for the author, please follow the link and comment on their blog: julianhi's Blog » R Tutorials.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)