Skip to content

Align two plots on a page

Mara Averick edited this page Oct 30, 2018 · 8 revisions

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

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

There are two stategies: use facetting, or create two separate plots and combine them on a page.

Dummy facetting

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)) + 
  facet_grid(panel~., scale="free") + 
  geom_line(data = d1, stat = "identity") + 
  geom_tile(data=d2, mapping=aes(colour=z, fill=z), stat = "identity")
p

Combining two plots

Alternatively, it may be easier to produce separate plots, and align them on the page. We illustrate the procedure with the gtable package, used internally for the layout of ggplot objects.

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))

p1 <-  ggplot(data = d1, mapping = aes(x = x, y = y)) + 
  geom_line(stat = "identity") 

p2 <-  ggplot(data = d2, mapping = aes(x=x, y=y, fill=z)) + 
  geom_tile()

## convert plots to gtable objects
library(gtable)
library(grid) # low-level grid functions are required
g1 <- ggplotGrob(p1)
g1 <- gtable_add_cols(g1, unit(0,"mm")) # add a column for missing legend
g2 <- ggplotGrob(p2)
g <- rbind(g1, g2, size="first") # stack the two plots
g$widths <- unit.pmax(g1$widths, g2$widths) # use the largest widths
# center the legend vertically
g$layout[grepl("guide", g$layout$name),c("t","b")] <- c(1,nrow(g))
grid.newpage()
grid.draw(g)

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

Clone this wiki locally