Combine Multiple Plots with patchwork


The patchwork package in R is an extension of the ggplot2 package, designed to simplify the process of combining multiple plots into a single layout.
This post showcases the key features of patchwork and provides a set of graph examples using the package.

Documentation

{patchwork}

Quick start


The patchwork package in R is an extension of the ggplot2 package, designed to simplify the process of combining multiple plots into a single layout.

It offers a set of operators that make it easy to specify complex layouts in a human-readable way.

✍️ author → Thomas Lin Pedersen

📘 documentationgithub

⭐️ more than 1000 stars on github

Installation


To get started with patchwork, you can install it directly from CRAN using the install.packages function:

install.packages("patchwork")

Basic usage


The patchwork package allows you to combine multiple plots using simple arithmetic operators like +, /, and |.

Here’s a basic example:

p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))
p1 + p2

Key features


→ Combining Plots

You can combine multiple plots using the + operator.

Example:

p1 + p2 + p1

→ Arranging Plots

Use the / operator to stack plots on top of each other.

Example:

p1 / p2

→ Nesting Plots

You can nest plots using parentheses.

Example:

(p1 + p2) / p1

→ Adding Titles and Annotations

patchwork allows you to add titles, subtitles, and captions to your combined plots.

Example:

p1 + p2 + plot_annotation(title = 'My Combined Plot')




❤️ 10 best R tricks ❤️

👋 After crafting hundreds of R charts over 12 years, I've distilled my top 10 tips and tricks. Receive them via email! One insight per day for the next 10 days! 🔥