```
library(ggplot2)
df <- data.frame(
x = 1:10, y1 = 1:10, y2 = (1:10)^2, y3 = (1:10)^3, y4 = (1:10)^4
)
p1 <- ggplot(df, aes(x, y1)) + geom_point()
p2 <- ggplot(df, aes(x, y2)) + geom_point()
p3 <- ggplot(df, aes(x, y3)) + geom_point()
p4 <- ggplot(df, aes(x, y4)) + geom_point()
p5 <- ggplot(mpg, aes(as.factor(year), hwy)) +
geom_boxplot() +
facet_wrap(~class, scales = "free_y")
# simple grid
plot_grid(p1, p2, p3, p4)
# simple grid with labels and aligned plots
plot_grid(
p1, p2, p3, p4,
labels = c('A', 'B', 'C', 'D'),
align="hv"
)
# manually setting the number of rows, auto-generate upper-case labels
plot_grid(p1, p2, p3,
nrow = 3,
labels = "AUTO",
label_size = 12,
align = "v"
)
# making rows and columns of different widths/heights
plot_grid(
p1, p2, p3, p4,
align = 'hv',
rel_heights = c(2,1),
rel_widths = c(1,2)
)
# aligning complex plots in a grid
plot_grid(
p1, p5,
align = "h", axis = "b", nrow = 1, rel_widths = c(1, 2)
)
# more examples
# \donttest{
#' # missing plots in some grid locations, auto-generate lower-case labels
plot_grid(
p1, NULL, NULL, p2, p3, NULL,
ncol = 2,
labels = "auto",
label_size = 12,
align = "v"
)
# can arrange plots on the grid by column as well as by row.
plot_grid(
p1, NULL, p2, NULL, p3,
ncol = 2,
byrow = TRUE
)
# can align top of plotting area as well as bottom
plot_grid(
p1, p5,
align = "h", axis = "tb",
nrow = 1, rel_widths = c(1, 2)
)
# other types of plots not generated with ggplot
p6 <- ~{
par(
mar = c(3, 3, 1, 1),
mgp = c(2, 1, 0)
)
plot(sqrt)
}
p7 <- function() {
par(
mar = c(2, 2, 1, 1),
mgp = c(2, 1, 0)
)
image(volcano)
}
p8 <- grid::circleGrob()
plot_grid(p1, p6, p7, p8, labels = "AUTO", scale = c(1, .9, .9, .7))
# }
```

Run the code above in your browser using DataLab