Skip to content

Align two plots on a page

baptiste edited this page Sep 2, 2010 · 8 revisions

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

Alternative

A function align.plots() is available in the ggExtra package that does just that: align two (or more) plots. It is a hack, where the size and position of each plot is adjusted with respect to its y-axis label and (optional) legend to align the plot panels. It does not work well with facetted plots for obvious reasons, and the vertical alignment is not implemented. Improvements to make this function more general have been proposed on the ggplot2 mailing list.

Note: The ggplot2 wiki is no longer maintained, please use the ggplot2 website instead!

Clone this wiki locally