Learn R Programming

cowplot (version 0.9.2)

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

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)

Examples

Run this code
# NOT RUN {
p1 <- ggplot(mpg, aes(manufacturer, hwy)) + stat_summary(fun.y="median", geom = "bar") +
         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(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 would could accomplish it.
ggdraw(aligned_plots[[1]]) +draw_plot(aligned_plots[[2]])
# }

Run the code above in your browser using DataLab