gtable for figure assembly: howto overlay a "ggplotGrob" with a "grid.text" label?

248 views
Skip to first unread message

Johannes Graumann

unread,
May 24, 2013, 2:27:25 PM5/24/13
to ggp...@googlegroups.com
Hello,

I've build a gtable like this:

paperDims <- list(DinA4=list(long=297,short=210))
# Total dimensions: A4 minus 20 mm in either direction
figWidth <- paperDims$DinA4$short - 20
figHeight <- paperDims$DinA4$long - 20
# These are the dimensions (mm) of the png included.
pngHeight <- 176.86
pngWidth <- 117.26
# Layout the gtable
# Prepare for the addition of inter-column/row space of 2.5 mm
tmpGTable <- gtable(
  widths=unit(x=c(pngWidth,figWidth-pngWidth-2.5),units="mm"),
  heights=unit(x=c(rep((pngHeight-5)/3,3),figHeight-pngHeight),units="mm"),
  name="Figure1")
# Add inter-column/raw space
tmpGTable <- gtable_add_col_space(tmpGTable,unit(2.5,units="mm"))
tmpGTable <- gtable_add_row_space(tmpGTable,unit(2.5,units="mm"))


Now I'm loading a ggplot into one of the cells like so:

tmpB <- ggplot(data=diamonds, aes(carat, price)) +
  xlim(0, 2) +
  geom_point()
tmpB <- tmpB + theme(plot.margin = unit(c(0,0,0,0), "mm"),plot.background=element_rect(fill="transparent"))
tmpGTable <- gtable_add_grob(x=tmpGTable,grobs=ggplotGrob(tmpB),t=1,l=3)
# Label
tmpLabel <- grid.text(label="B",x=0,y=1,hjust=unit(0,"mm"),vjust=unit(1,"mm"))
tmpGTable <- gtable_add_grob(x=tmpGTable,grobs=tmpLabel,t=1,l=3)


For my life I can't make that "B" show up on th plot no matter what I do, play around with z, etc.

This is particularly puzzling as the "A" panel of the figure contains an embedded png for which the analogous overlay with "A" works.

Can anyone of the ggplot-enclined grid-wizzards shed some light on how to get this done?

Thank you for any hints.

Sincerely, Joh

Johannes Graumann

unread,
May 24, 2013, 3:05:51 PM5/24/13
to ggp...@googlegroups.com
Solved it like so:


On Friday, May 24, 2013 9:27:25 PM UTC+3, Johannes Graumann wrote:
tmpB <- ggplot(data=diamonds, aes(carat, price)) +
  xlim(0, 2) +
  geom_point()
tmpB <- tmpB + theme(plot.margin = unit(c(0,0,0,0), "mm"),plot.background=element_rect(fill="transparent"))

tmpB <- ggplotGrob(tmpB)

tmpLabel <- grid.text(label="B",x=0,y=1,hjust=unit(0,"mm"),vjust=unit(1,"mm"))
tmpB <- gTree(children=gList(tmpB,tmpLabel))

tmpGTable <- gtable_add_grob(x=tmpGTable,grobs=tmpE,t=7,l=1,r=3)

This is particularly puzzling as the "A" panel of the figure contains an embedded png for which the analogous overlay with "A" works.
 This only worked because "A" is spanning rows 1-5 and I had accidentally placed the text annotation grob in row 1 only ...

Sweet - now I can construct my entire figures using ggplot2 & gtable and even embed png's were such drawings are appropriate!

Joh
Reply all
Reply to author
Forward
0 new messages