Inserting subplots

Posted on Updated on

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:

Figure 1

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.

## 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..

## ..and insert subset
print(plotablmsmall, vp = subvp)

plot of chunk dat subplots