It is possible to create inset graphs?

Sam picture Sam · Mar 7, 2011 · Viewed 18.2k times · Source

I know that when you use par( fig=c( ... ), new=T ), you can create inset graphs. However, I was wondering if it is possible to use ggplot2 library to create 'inset' graphs.

UPDATE 1: I tried using the par() with ggplot2, but it does not work.

UPDATE 2: I found a working solution at ggplot2 GoogleGroups using grid::viewport().

Answer

Richie Cotton picture Richie Cotton · Mar 7, 2011

Section 8.4 of the book explains how to do this. The trick is to use the grid package's viewports.

#Any old plot
a_plot <- ggplot(cars, aes(speed, dist)) + geom_line()

#A viewport taking up a fraction of the plot area
vp <- viewport(width = 0.4, height = 0.4, x = 0.8, y = 0.2)

#Just draw the plot twice
png("test.png")
print(a_plot)
print(a_plot, vp = vp)
dev.off()