4.5 C
London
Thursday, December 19, 2024
HomeTidyverse in Rggplot2 in RHow to Create Side-by-Side Plots in ggplot2

How to Create Side-by-Side Plots in ggplot2

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

Often you may want to create two plots side-by-side using the ggplot2 package in R. Fortunately this is easy to do with the help of the patchwork package.

#install ggplot2 and patchwork packages
install.packages('ggplot2')
install.packages('patchwork')

#load the packages 
library(ggplot2)
library(patchwork)

This tutorial shows several examples of how to use these packages to create side-by-side plots.

Example 1: Two Side-by-Side Plots

The following code shows how to create two side-by-side plots using the R built-in iris dataset:

#create box plot
plot1 #create density plot
plot2 #display plots side by side
plot1 + plot2 

Side-by-side plots in ggplot2 in R

Example 2: Three Side-by-Side Plots

The following code shows how to create three side-by-side plots using the R built-in iris dataset:

#create box plot
plot1 #create density plot
plot2 #create scatterplot 
plot3 #display three plots side by side
plot1 + plot2 + plot3

Three side-by-side plots in ggplot2

Example 3: Two Stacked Plots

The following code shows how to create two stacked plots, one on top of the other:

#create box plot
plot1 #create density plot
plot2 #display plots stacked on top of each other
plot1 / plot2 

Two stacked plots in ggplot2

Example 4: Add Titles, Subtitles, and Captions

The following code shows how to add titles, subtitles, and captions to the plots:

#create box plot
plot1 #create density plot
plot2 #display plots side by side with title, subtitle, and captions
patchwork This is a title',
  subtitle = 'This is a subtitle that describes more information about the plots',
  caption = 'This is a caption'
)

Side by side plots in ggplot2 with titles and subtitles

You can find more R tutorials here.

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories