Add a background png image to ggplot2

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

2 thoughts on “Add a background png image to ggplot2

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s