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:

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



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: