Written and maintained by CASRAI Editorial Board
Published · Last updated
On this page
Researchers preparing manuscripts for peer-reviewed journals frequently need to combine multiple subplots into unified multi-panel figures (panels A, B, C, and D) with consistent scaling, aligned axes, and shared legends. In R programming in research, the cowplot package provides a streamlined extension to ggplot2 designed specifically to arrange plots into publication-ready composite figures, align misaligned coordinate axes across panels, overlay custom annotations, and enforce clean visual themes without modifying global graphics defaults.
Ask CASRAI · free to tryQuestion about this guide? Ask CASRAI answers with linked sources. 2 free questions a day, no account.
What it is used for in research
Developed by Claus O. Wilke, cowplot (standing for Claus O. Wilke’s plot package) provides publication-tailored layout and annotation utilities for R users. While base ggplot2 excels at single plots and small multiples via faceting, empirical scientific workflows routinely require combining disparate plot types—such as placing a scatter plot of experimental observations alongside a boxplot of summary statistics and a continuous dose-response curve—into a single composite figure.
In academic publishing, journals enforce strict figure guidelines: subpanels must carry explicit identifying labels, axes with identical units must align precisely across rows or columns, and legends should not be needlessly duplicated across adjacent panels. In quantitative analysis and computational reproducibility, cowplot addresses these requirements through four core research capabilities:
- Multi-panel grid composition: The
plot_grid()function arranges independent ggplot objects into row-and-column grids with automatic or custom alphanumeric subfigure tags. - Complex coordinate alignment: The
alignandaxisarguments align plot margins both vertically and horizontally, preventing axis label length discrepancies from shifting plot boundaries. - Shared legend extraction: The
get_legend()helper extracts the legend grob (graphical object) from an individual plot so it can be rendered once beside or below a composite grid. - Canvas drawing and insets: Built on the
ggdraw()canvas layer,cowplotenables researchers to place inset subplots, watermarks, corporate/funder logos, and mathematical annotations at arbitrary coordinate locations. - Publication-ready themes: Functions such as
theme_cowplot()andtheme_half_open()deliver clean, uncluttered visual styling with clear axis lines and legible typography suitable for print and digital manuscripts.
How to install or access it
The stable release of cowplot is distributed through the Comprehensive R Archive Network (CRAN). To install the package from official CRAN repositories within an active R session or RStudio environment, execute:
# Install cowplot from official CRAN mirrors
install.packages('cowplot')
To maintain environment stability and lock package versions across collaborative research teams, manage dependencies using renv package management by recording the installed package state:
# Record the installed cowplot version in your renv lockfile
renv::snapshot()
For projects requiring prerelease features or developmental patches, install the development build directly from the author’s verified GitHub repository using remotes:
# Install development version from GitHub
# install.packages('remotes')
remotes::install_github('wilkelab/cowplot')
Step-by-step instructions
This walkthrough demonstrates how to build, align, label, and export a multi-panel research figure from separate ggplot objects.
1. Load required libraries and configure themes
Load ggplot2 and cowplot. In modern releases (cowplot 1.0.0 and newer), attaching cowplot does not overwrite the default ggplot2 theme globally unless explicitly requested, preserving full reproducibility.
library(ggplot2)
library(cowplot)
# Optional: set cowplot as the global session theme
# theme_set(theme_cowplot(font_size = 12))
2. Generate individual subplots
Create two distinct subplots using standard datasets or experimental measurements. Apply theme_cowplot() to establish clean publication styling:
# Panel A: Scatter plot of engine displacement versus highway mileage
p_scatter <- ggplot(mpg, aes(x = displ, y = hwy, color = drv)) +
geom_point(size = 2.5, alpha = 0.8) +
scale_color_brewer(palette = 'Dark2', name = 'Drive') +
labs(x = 'Displacement (L)', y = 'Highway MPG') +
theme_cowplot(font_size = 11)
# Panel B: Boxplot of highway mileage across drive classes
p_box <- ggplot(mpg, aes(x = drv, y = hwy, fill = drv)) +
geom_boxplot(alpha = 0.8, outlier.shape = 21) +
scale_fill_brewer(palette = 'Dark2', name = 'Drive') +
labs(x = 'Drive Type', y = 'Highway MPG') +
theme_cowplot(font_size = 11)
3. Combine plots into an aligned multi-panel grid
Use plot_grid() to arrange the subplots side by side. Specify labels = 'AUTO' to generate uppercase subpanel labels (A, B) and set align = 'h' with axis = 'b' to ensure horizontal and baseline alignment:
# Combine into a two-column grid with automatic uppercase labels
combined_grid <- plot_grid(
p_scatter + theme(legend.position = 'none'),
p_box + theme(legend.position = 'none'),
labels = 'AUTO',
label_size = 14,
ncol = 2,
align = 'h',
axis = 'b'
)
4. Extract and position a single shared legend
To eliminate duplicate legends between panels sharing the same categorical aesthetic, extract one legend grob using get_legend() and append it to the grid:
# Extract the legend from the scatter plot
shared_legend <- get_legend(
p_scatter + theme(legend.box.margin = margin(0, 0, 0, 10))
)
# Place the combined panels and the single shared legend side by side
final_figure <- plot_grid(
combined_grid,
shared_legend,
ncol = 2,
rel_widths = c(1, 0.2)
)
5. Save publication graphics with save_plot
Use cowplot’s dedicated save_plot() function instead of generic device calls. save_plot() calculates appropriate aspect ratios and prevents font distortion across multi-panel layouts:
# Export vector PDF formatted for standard manuscript dimensions
save_plot(
filename = 'figure1_multipanel.pdf',
plot = final_figure,
ncol = 2,
nrow = 1,
base_width = 4.5,
base_height = 4.0,
dpi = 300
)
Output and how to read it
When plot_grid() or ggdraw() executes, the returned object is a compound gtable/ggplot object that renders into the active graphical display device or exports via save_plot(). Evaluating the generated output involves verifying three distinct structural criteria:
- Panel label hierarchy: Subpanel labels (A, B, C) appear at the upper-left corner of each plotting region by default (controlled by
label_x = 0andlabel_y = 1). Verify that labels do not overlap plot titles or y-axis tick values. - Coordinate boundary alignment: In unaligned grids, plots with differing numeric digit widths on their y-axis (e.g., 0–10 versus 10,000–50,000) produce uneven plotting canvas widths. When
align = 'hv'andaxis = 'tblr'are set, the inner plotting boxes align exactly to identical pixel/point coordinates, creating consistent vertical and horizontal datum lines. - Typography and contrast: Under
theme_cowplot(), default gray background grids are stripped, and high-contrast black axis lines (half-open box) frame the data. Text size scales cleanly according to thefont_sizeparameter passed to the theme.
Troubleshooting
Global theme override collisions
Problem: In scripts written prior to cowplot version 1.0.0, loading library(cowplot) automatically changed the default ggplot2 theme globally, stripping grid lines from subsequent plots. Conversely, calling theme_set(theme_gray()) or adding theme() before theme_cowplot() can unexpectedly overwrite desired font specifications.
Solution: Since cowplot 1.0.0, the package respects default ggplot themes upon loading. Apply + theme_cowplot() explicitly to individual plots or call theme_set(theme_cowplot()) deliberately at the start of your analysis script. Always place custom theme() modifications after theme_cowplot() in your ggplot chain, as ggplot applies theme layers sequentially from left to right.
Axis misalignment despite setting align = ‘hv’
Problem: Plots appear misaligned horizontally or vertically even though align = 'hv' was specified in plot_grid().
Solution: By default, align without the axis parameter attempts to align overall plot bounding boxes rather than internal coordinate borders. Set the axis argument explicitly (e.g., axis = 'tblr' for top, bottom, left, and right, or axis = 'bt' for vertical stacking) to force margin alignment across differing axis tick label widths.
Extracted legend returns NULL or empty grob
Problem: Calling get_legend(my_plot) returns NULL or an empty graphical object, causing blank space in the multi-panel layout.
Solution: Verify that the source plot passed into get_legend() actually contains a visible legend. If theme(legend.position = 'none') was applied to the plot prior to extraction, no legend grob exists. Extract the legend from a plot version with legend.position = 'right' (or 'bottom') first, then suppress the legend on the version passed into the data panel grid. In ggplot2 versions 3.5.0+, you can also use cowplot’s get_plot_component(p, 'guide-box') to target the legend container directly.
Free alternatives
Several packages in the broader R ecosystem provide figure composition and layout tools. The following table compares cowplot with other prominent open-source alternatives available for research data workflows across free statistical software environments:
| Package | Primary Layout Paradigm | Shared Legend Handling | Custom Insets and Drawing | Best Suited For |
|---|---|---|---|---|
| cowplot | Function-based grid assembly via plot_grid() |
Manual extraction via get_legend() and re-assembly as a grid element |
Native canvas drawing via ggdraw() and draw_plot() |
Publication-ready figure panels, complex axis alignment, and arbitrary image or inset overlays |
| patchwork | Mathematical operator syntax (+, /, |) |
Automated collection via plot_layout(guides = 'collect') |
Overlay support using inset_element() |
Rapid interactive figure composition and expressive formula-driven subpanel layouts |
| gridExtra | Grid layout functions (grid.arrange(), arrangeGrob()) |
Requires manual extraction of guide-box grobs through gtable |
Requires low-level grid viewport coordinates |
Combining ggplot objects with non-ggplot graphical elements, such as tables (tableGrob) |
FAQ
Does loading cowplot automatically change all ggplot2 themes?
No. In cowplot versions 1.0.0 and later, attaching the package via library(cowplot) does not overwrite the global ggplot2 default theme. Researchers who want cowplot styling across all session plots must explicitly invoke theme_set(theme_cowplot()).
How do I automatically label multi-panel figures A, B, and C in cowplot?
Pass labels = 'AUTO' into plot_grid() to generate uppercase panel identifiers (A, B, C…). To generate lowercase letters (a, b, c…), pass labels = 'auto'. Custom vectors such as labels = c('Fig 1A', 'Fig 1B') are also supported.
Can cowplot combine plots with differing dimensions or aspect ratios?
Yes. The rel_widths and rel_heights parameters in plot_grid() accept numeric vectors defining the relative proportions of each column and row. For example, rel_widths = c(2, 1) makes the first column twice as wide as the second.
How do I align plots when one y-axis label pushes the plot area inward?
Set align = 'hv' and specify the margin axes via axis = 'tblr' (top, bottom, left, right) inside plot_grid(). This aligns the actual plot panels rather than the outer bounding boxes, ensuring straight vertical axis baselines across panels.
How does cowplot differ from the patchwork package in R?
While patchwork uses arithmetic operators (such as p1 + p2 or p1 / p2) for intuitive layout creation, cowplot uses a coordinate-canvas approach (ggdraw and plot_grid) that provides fine-grained control over axis alignment, inset subplots, and arbitrary graphical overlays.
Sources
- CRAN: cowplot: Streamlined Plot Theme and Plot Annotations for ‘ggplot2’ (Version 1.2.0, Author: Claus O. Wilke), checked 2026-11-10.
- Claus O. Wilke Lab: cowplot Official Documentation, checked 2026-11-10.
- Wilke Lab Vignette: Arranging plots into a grid, checked 2026-11-10.
- Wilke Lab Vignette: Aligning plots, checked 2026-11-10.







