Creating subplots in R
Let's discuss how to insert a subplot in an existing plot. Most of the following is actually taken from Hadley Wickam's book ggplot2: Elegant Graphics for Data Analysis.
Suppose we have two graphs, plotlm500 (LHS graph) and plotablm (RHS graph) as shown in the figure below:
Now let's assume we want to embed the right-hand side graph in the left-hand side graph. The way to procede is to use viewports as described below.
library(ggplot2) library(grid) ## Create plot + subplots using viewports subvp <- viewport(width = 0.4, height = 0.4, x = 0.72, y = 0.3) ## Shrink plot margins of small graph plotablmsmall <- plotablm + theme_gray(9) + ## labs(x = NULL, y = NULL)+ theme(plot.margin = unit(rep(0, 4), "lines"), legend.position = "none") ## Plot bigger graph.. plotlm500 ## ..and insert subset print(plotablmsmall, vp = subvp)