2
votes

I've been trying to edit some plots created by ggplot2 using the functions provided by the packages grid and gridExtra. I realize that ggplot2 alone can make some really nice multifaceted plots. However, in some instances I like to create individual plots and then combine then together later on. While trying to do just that, I came across some unexpected behavior using cbind() with grid.draw() or grid.arrange() when using a ggplot2 graph that had been edited. Below is the code for an MWE:

#Load libraries
    library(ggplot2); library(gridExtra)

#Load data
    data(mtcars)

#Ggplot
    p = qplot(wt,mpg,data=mtcars,color=cyl)
    grob = ggplotGrob(p)

#Bold xlabel
    grobEdited = editGrob(grid.force(grob),gPath("xlab","GRID.text"),grep=TRUE,gp=gpar(fontface="bold"))

#Visualize
    grid.newpage()
    grid.draw(grobEdited)

enter image description here

It worked as expected. Now to illustrate the issue, lets cbind() two of the same edited ggplot2 graphs:

#Cbind example with edited graphs
    grid.newpage()
    grid.draw(cbind(grobEdited,grobEdited))

enter image description here

It didn't work as expected! Now test cbind() on the unedited graphs:

#Cbind example with grob
    grid.newpage()
    grid.draw(cbind(grob,grob)) 

enter image description here

Works as expected. I'm new to gridded figures, so is there something I'm doing wrong?

1
The issue is with the grid.force() call. Documentation suggests that drawing the result may not make sense in a different drawing context. Are you able to remove that part of the code?Ryan Morton
@ryan-morton grid.force() allows the editing functions to have access to all of the grobs in the ggplot2 graph, so in this context I believe it is necessary. I guess I could manually edit the grob w/o using the editing functions (which will make thinks a lot more difficult).user13317
Maybe try cbinding before the edit.. grobEdited = editGrob(grid.force(cbind(grob, grob)), gPath("xlab","GRID.text"), global=TRUE, grep=TRUE,gp=gpar(fontface="bold", col="red"))user20650
(or maybe grid.arrange is okay for your needs)user20650

1 Answers

1
votes

I'm posting an answer following the comment from @user20650. The easiest workaround is to cbind() the ggplot2 graphs before editing them using the editing functions provided by grid or gridExtra:

#Edit after cbind()                              
    grobEdited = editGrob(grid.force(cbind(grob,grob)),gPath("xlab","GRID.text"),global=TRUE,grep=TRUE,gp=gpar(fontface="bold"))

#Visualize
    grid.newpage()
    grid.draw(grobEdited)

enter image description here