Add a background png image to ggplot2

February 16, 2014
By

(This article was first published on julianhi's Blog » R Tutorials, and kindly contributed to R-bloggers)

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 his blog: julianhi's Blog » R Tutorials.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.