2

My question is similar to this one; I wish to annotate each facet with a different image in the bottom-left corner.

Using gtable_add_grob I am able to replace the facets with images like so:

library(ggplot2)
library(gtable)
library(RCurl)
library(png)

d <- expand.grid(x=1:2,y=1:2, f=letters[1:2])
p <- qplot(x,y,data=d) + facet_wrap(~f)

g <- ggplot_gtable(ggplot_build(p))
shark <- readPNG(getURLContent("http://i.imgur.com/EOc2V.png"))
tiger <- readPNG(getURLContent("http://i.imgur.com/zjIh5.png"))

facets <- grep("panel", g$layout$name)
new_grobs <- list(rasterGrob(shark, width=1, height=1),
                  rasterGrob(tiger, width=1, height=1))
g2 <- with(g$layout[facets,],
          gtable_add_grob(g, new_grobs,
                          t=t, l=l, b=b, r=r, name="pic_predator") )        
grid.draw(g2)

enter image description here

However, what I'm really wanting is something like this, but I can't figure out the appropriate gtable command to shrink and place the image on each facet:

enter image description here

I'm happy for the solution to not use gtable, if that is necessary.

Community
  • 1
  • 1
luser
  • 355
  • 4
  • 14
  • 1
    You can control their size by changing the width and height parts when you create `new_grobs`, e.g., `new_grobs <- list(rasterGrob(shark, width=0.15, height=0.05), rasterGrob(tiger, width=0.15, height=0.05))` looks about right size-wise. Then you just need to adjust their placement. – ulfelder Aug 13 '15 at 12:39
  • 1
    Thanks, this got me playing around with `rasterGrob` and lead to finding a solution. – luser Aug 13 '15 at 13:05

1 Answers1

0

Controlling the width and height arguments in rasterGrob shrinks the image, and setting the x and y positions (or using hjust or vjust I suppose) controls the placement of the image.

library(ggplot2)
library(gtable)
library(RCurl)
library(png)

d <- expand.grid(x=1:2,y=1:2, f=letters[1:2])
p <- qplot(x,y,data=d) + facet_wrap(~f)

g <- ggplot_gtable(ggplot_build(p))
shark <- readPNG(getURLContent("http://i.imgur.com/EOc2V.png"))
tiger <- readPNG(getURLContent("http://i.imgur.com/zjIh5.png"))

facets <- grep("panel", g$layout$name)
new_grobs <- list(rasterGrob(shark, width=.2, height=.05, x = .2, y = .05),
                  rasterGrob(tiger, width=.2, height=.05, x = .2, y = .05))
g2 <- with(g$layout[facets,],
          gtable_add_grob(g, new_grobs,
                          t=t, l=l, b=b, r=r, name="pic_predator") )        
grid.draw(g2)

enter image description here

luser
  • 355
  • 4
  • 14