Last week when trying to generate some awsome summary graphic, I came across the painful ordeal of trying to combine
ggplot elements with a number of regular R graphic elements.
First things first, I had used
grid.arrange module from
gridExtra package to juxtapose ggplot elements in a panel figure. Furthermore, I had combined regular R [read non-ggplot] figures thru the good old
We will be making calls to
viewport module from the
gridBase package to generate---guess what---view ports into which ggplot objects are plotted. Interestingly,
ggplot elements need not be a single simple
ggplot object, but could be an arrangement of multiple objects bundled together using
arrangeGrob module from
But before (and I emphasize before!) all that, we have to plot all regular R graphic elements in their respective layouts using
par. Keep in mind that we have to save space for the
ggplot elements to be added; this is possible by making calls to
library(gridBase) library(ggplot2) # say I would like to have my regular R graphic in top-right quadrant par(mfrow = c(2,2), mar=c(0,0,0,0), oma=c(0,0,0,0)) # leave top-left quadrant empty! plot.new() # plot regular R graphic in top-right quadrant plot(seq(1:10), seq(1:10), pch = 20) # now add the first ggplot element which is going to take # up the left two quadrants vp <- viewport(height = unit(1,"npc"), width=unit(0.5, "npc"), just = c("left","top), y = 1, x = 0.5) print(my.first.ggplot.obj, vp = vp) # add the second ggplot element in the bottom right quadrant vp <- viewport(height = unit(1,"npc"), width=unit(0.5, "npc"), just = c("left","top), y = 0.5, x = 0.5) print(my.second.ggplot.obj, vp = vp)
Voila! Here is the awesome-looking panel figure!