# Align two plots on a page

##### Clone this wiki locally

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)