Learn R Programming

cowplot (version 1.1.3)

align_plots: Align multiple plots vertically and/or horizontally

Description

Align the plot area of multiple plots. Inputs are a list of plots plus alignment parameters. Horizontal or vertical alignment or both are possible. In the simplest case the function will align all elements of each plot, but it can handle more complex cases as long as the axis parameter is defined. In this case, alignment is done through a call to align_margin(). The function align_plots is called by the plot_grid() function and is usually not called directly, though direct calling of the function is useful if plots with multiple y-axes are desired (see example).

Usage

align_plots(
  ...,
  plotlist = NULL,
  align = c("none", "h", "v", "hv"),
  axis = c("none", "l", "r", "t", "b", "lr", "tb", "tblr"),
  greedy = TRUE
)

Arguments

...

List of plots to be aligned.

plotlist

(optional) List of plots to display. Alternatively, the plots can be provided individually as the first n arguments of the function align_plots (see plot_grid examples).

align

(optional) Specifies whether graphs in the grid should be horizontally ("h") or vertically ("v") aligned. Options are align="none" (default), "hv" (align in both directions), "h", and "v".

axis

(optional) Specifies whether graphs should be aligned by the left ("l"), right ("r"), top ("t"), or bottom ("b") margins. Options are axis="none" (default), or a string of any combination of "l", "r", "t", and/or "b" in any order (e.g. axis="tblr" or axis="rlbt" for aligning all margins)

greedy

(optional) Defines the alignment policy when alignment axes are specified via the axis option. greedy = TRUE tries to always align by adjusting the outmost margin. greedy = FALSE aligns all columns/rows in the gtable if possible.

Examples

Run this code
library(ggplot2)

p1 <- ggplot(mpg, aes(manufacturer, hwy)) + stat_summary(fun.y="median", geom = "bar") +
  theme_half_open() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust= 1))
p2 <- ggplot(mpg, aes(manufacturer, displ)) + geom_point(color="red") +
  scale_y_continuous(position = "right") +
  theme_half_open() + theme(axis.text.x = element_blank())

# manually align and plot on top of each other
aligned_plots <- align_plots(p1, p2, align="hv", axis="tblr")

# Note: In most cases two y-axes should not be used, but this example
# illustrates how one could accomplish it.
ggdraw(aligned_plots[[1]]) + draw_plot(aligned_plots[[2]])

Run the code above in your browser using DataLab