Align two plots on a page - brodieG/ggplot2 GitHub Wiki

Goal: two plots with different meaning (y-scale, geom, etc.) need to be aligned for they share a common x-axis.

This is currently difficult to achieve in ggplot2 (the latticeExtra package, base graphics, and raw Grid can be considered as an alternative). However, it is often possible to obtain good results by creating a dummy facetting of the data as in the following example:

library(ggplot2)
x <- seq(1992, 2002, by=2)

d1 <- data.frame(x=x, y=rnorm(length(x)))
xy <- expand.grid(x=x, y=x)
d2 <- data.frame(x=xy$x, y=xy$y, z= jitter(xy$x + xy$y))

d1$panel <- "a"
d2$panel <- "b"
d1$z <- d1$x

d <- rbind(d1, d2)

p <- ggplot(data = d, mapping = aes(x = x, y = y))
p <- p + facet_grid(panel~., scale="free")
p <- p + layer(data= d1,  geom = c( "line"), stat = "identity")
p <- p + layer(data=d2, mapping=aes(colour=z, fill=z),  geom =
c("tile"), stat = "identity")
p

This produces the following plot:

plot