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
1 2 |
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:
Add an image
First of all we need to load the picture. Just place it in your working directory and load it with:
1 |
img <- readPNG("sochi-logo.png") |
And add a raster:
1 |
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.
1 2 3 4 5 6 7 8 9 |
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: