several ggplot2 plots on top on an image

736 views Asked by At

I have this nice custom plot function based on ggplot2

What I would now like to do, is to place several plots drawn with this function on top of a background image (loaded in as a png).

I do not want to place the plots on a regular grid, but rather at select locations on the image.

(An example of such a plot is can be seen on http://www.climatechange2013.org/images/figures/WGI_AR5_Fig10-21.jpg)

It seems to me that I will need to have each of my plots drawn within a distinct environment, and a method for placing these environments at select coordinates on the image.

Can anyone direct me to the right packages/tutorial/blogs/etc that could be of use for this?

Sincerely, Halldór

2

There are 2 answers

3
Rentrop On

Have a look at Embedded Plots via ggplot: http://vita.had.co.nz/papers/embedded-plots.pdf and ggsubplot-Packages.

Or do it "by hand" via-ggplot2::annotation_raster.
Taking this Image: http://pixabay.com/static/uploads/photo/2012/04/16/12/34/squares-35798_640.png

require(ggplot2)
require(png)
library(RCurl)
myurl <- "http://pixabay.com/static/uploads/photo/2012/04/16/12/34/squares-35798_640.png"
mypng <-  readPNG(getURLContent(myurl))

df <- data.frame(x = rnorm(10), y = rnorm(10))

ggplot(df, aes(x=x,y=y)) + 
  annotation_raster(mypng, xmin=min(df$x), xmax = max(df$x), ymin=min(df$y), ymax=max(df$y)) + 
  geom_point()

Now you can add whatever layer geom_... you want. Probably you need to modify xmin, xmax, ymin, ymax accordingly.

enter image description here

3
DatamineR On

Using an exemplary image here one approach:

library(png)
ima <- readPNG("C:/Users/MyPC/Desktop/rus.png")
png <- "C:/Users/MyPC/Desktop/rus.png"
ima <- readPNG(png)
library(ggplot2)

tm <- theme(
    panel.background = element_rect(fill = "transparent",colour = "black"), # or theme_blank()
    panel.grid.minor = element_blank(), 
    panel.grid.major = element_blank(),
    plot.background = element_rect(fill = "transparent",colour = NA)
)

plot.new()
lim <- par()
rasterImage(ima, lim$usr[1], lim$usr[3], lim$usr[2], lim$usr[4])

library(grid)
vp <- viewport(.25, 0.65, width =.3, height = .3)
pl <- ggplot(mtcars, aes(x = mpg)) + geom_histogram() + tm
print(pl, vp = vp)

pl2 <- ggplot(mtcars, aes(x = mpg, y = wt)) + geom_line() + tm
vp2 <- viewport(.75, 0.65, width =.3, height = .3)
print(pl2, vp = vp2)

pl3 <- ggplot(mtcars, aes(x = mpg, y = wt)) + geom_line() + tm
vp3 <- viewport(.5, 0.4, width =.3, height = .3)
print(pl3, vp = vp3)

enter image description here