Join our Community Groups and get customized solutions Join Now! Watch Tutorials Youtube

ggplot2 multiple plots in R

Learn to combine multiple ggplots into a single plot using the facet functions in ggplot2 and the ggpubr package.

Key Points

  • To create multiple panels within one plot based on one or more factors, you can use one of the faceting functions: facet_wrap() or facet_grid().
  • To arrange multiple plots in a simple grid layout using the grid system, use the gridExtra package and the grid.arrange() function.
  • To create complex layouts with shared axes and annotations using the ggplot2 system, you can use the cowplot package and the plot_grid() function.
  • To arrange multiple plots with common features and themes using the ggplot2 system, you can use the ggpubr package and the ggarrange() function.
  • To export the arranged plots to a file in various formats, you can use the ggsave() function.
ggplot2 multiple plots in R

Table

Function Description
facet_wrap() Creates multiple panels within one plot based on one factor
facet_grid() Creates multiple panels within one plot based on two factors grid
grid.arrange() Arranges multiple plots in a grid layout using the grid system
plot_grid() Arranges multiple plots in a grid layout using the ggplot2 system
ggarrange() Arranges multiple plots in a grid layout with common features and themes using the ggplot2 system

If you are working with data visualization in R, you have probably heard of ggplot2, one of the most popular and powerful packages for creating graphs. But what if you want to create multiple plots on the same page?

How can you arrange multiple plots using ggplot2 neat and organized?

In this article, I will show you how to produce multiple plots using ggplot2 and arrange them on a single page or multiple pages. You will learn to use different packages and functions to combine multiple ggplot in various layouts, such as grid, facet, or custom. You will also learn how to align the plot panels, add captions and annotations, and export the arranged plots to a file.

This article is worth reading because it will help you to create more complex and informative visualizations using ggplot2. You can compare different plot, show different aspects of the same data, or create a dashboard of graphs. You will also learn some tips and tricks for data manipulation and graphical customization using ggplot2.

What is ggplot2?

ggplot2 is a popular R package for data visualization that implements the grammar of graphics. It allows you to create graphs by specifying your plot's aesthetic mapping, geometric objects, statistical transformations, scales, coordinates, facets, and themes. Add labels, legends, titles, and other elements to your graph.

ggplot2 is based on the idea that a plot is a layered object that can be modified by adding or removing components. You can create a basic plot using the ggplot() function and then add layers of geoms, stats, scales, etc., using the + operator. You have to first install the library by using the install.packages function, read more How to Import and Install Packages in R: A Comprehensive Guide. For example, the following code creates a scatter plot of sepal.length vs sepal.width for the iris dataset:

install.packages("ggplot2")
library(ggplot2)
data(iris)
names(iris)
p1 <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point()
p1
A scatter plot of sepal.length vs sepal.width for the iris dataset 

You can see that ggplot2 automatically creates a default theme, axes, and legend for your plot. You can customize these elements by adding more layers or modifying the existing ones.

How to Arrange Multiple Plots Using ggplot2?

One of the advantages of ggplot2 is that it allows you to create multiple plots from the same data or different data sources and arrange them on a single page or multiple pages. This can be useful for comparing different plots, showing different aspects of the same data, or creating a dashboard of graphs.

Depending on your needs and preferences, there are several ways to arrange multiple plots using ggplot2. 

In this article, I will cover four main methods:

  • Using the facet_*() functions to create multiple panels within one plot
  • Using the gridExtra package to arrange multiple plots in a grid layout
  • Using the cowplot package to create complex layouts with shared axes and annotations
  • Using the ggpubr package to arrange multiple plots with common features and themes

Each method has advantages and disadvantages, so choose the one that best suits your purpose. Let’s see how each method works in detail.

How to Use the facet_*() Functions to Create Multiple Panels Within One Plot?

One of the simplest ways to create multiple plots using ggplot2 is to use one of the faceting functions: facet_wrap() or facet_grid(). These functions allow you to split your data into subsets based on one or more factors and create multiple panels (or facets) within one plot. Each panel shows a subset of the data with its axes and scales.

The faceting functions are useful when you want to compare different groups or levels of your data within one plot. For example, if you want to compare the scatter plots of sepal.length vs sepal.width for each species of iris, you can use facet_wrap() as follows:

p2 <- p1 + facet_wrap(~ species)
p2
A scatter plot of sepal.length vs sepal.width for each species of iris

You can see that ggplot2 creates three panels, one for each species (setosa, versicolor, and virginica). Each panel has its own x-axis and y-axis labels and scales. You can also see that ggplot2 adds a strip with the name of the factor (species) above each panel. 

Change the number of rows or columns of panels

You can customize the appearance and behavior of the facets by using various arguments in the faceting functions. For example, you can change the number of rows or columns of panels by using the nrow or ncol arguments, respectively. You can also change the direction of the panels by using the dir argument. For example, the following code creates two rows of panels and arranges them horizontally:

p3 <- p1 + facet_wrap(~ species, nrow = 2, dir = "h")
p3

A scatter plot of sepal.length vs sepal.width for each species of iris arranged in two rows

Grid of Panels based on Two Factors

You can also use facet_grid() to create a grid of panels based on two factors. For example, if you want to compare the scatter plots of sepal.length vs sepal.width for each combination of species and petal width, you can use facet_grid() as follows:
p4 <- p1 + facet_grid(Species ~ cut(Petal.Width, breaks = c(0, 1, 2, 3)))
p4

A scatter plot of sepal.length vs sepal.width for each combination of species and petal width

You can see that ggplot2 creates a grid of 9 panels, one for each combination of species (setosa, versicolor, and virginica) and petal width ((0,1], (1,2], (2,3]). Each panel has its own x-axis and y-axis labels and scales. You can also see that ggplot2 adds strips with the names of the factors (species and petal.width) above and to the right of each panel.

Customize the Appearance and Behavior of the Grid

You can customize the appearance and behavior of the grid by using various arguments in the faceting function. For example, you can change the grid layout by using the layout argument. You can also change the alignment of the axes by using the scales argument. For example, the following code creates a grid with three columns and four rows and aligns the x-axes across all panels:

p5 <- p1 + facet_grid(Species ~ cut(Petal.Width, breaks = c(0, 1, 2, 3)), scales = "free_x")
p5

A scatter plot of sepal.length vs sepal.width for each combination of species and petal width arranged in a grid with three columns and four rows and aligned x-axes

The faceting functions are convenient, and easy to create multiple panels within one plot. However, they are limited when creating more complex layouts or combining plots. 

For example, you cannot use faceting functions to create plots with different geoms or data sources. You cannot add annotations or captions to individual panels or the plot. In these cases, you must use other methods to arrange multiple plots using ggplot2.

How to Use the gridExtra Package to Arrange Multiple Plots in a Grid Layout?

Another way to create multiple plots using ggplot2 is to use the gridExtra package. This package provides functions to arrange multiple plots in a grid layout using the grid system. The grid system is a low-level graphical system that allows you to create and manipulate graphical objects (such as plots) on a page.

The main function in the gridExtra package is grid.arrange(). This function allows you to arrange multiple plots (or other grid objects) in a grid layout with a specified number of rows or columns. For example, if you want to arrange four different plots (p1, p2, p3, and p4) in a grid with two rows and two columns, you can use grid.arrange() as follows:

library(gridExtra)
grid.arrange(p1, p2, p3, p4, nrow = 2, ncol = 2)

Four different plots arranged in a grid with two rows and two columns

You can see that gridExtra arranges the four plots in a grid with two rows and two columns. Each plot has its axes and scales. You can also see that gridExtra adds labels (a, b, c, and d) to each plot.

Change the Size and Position of each plot

You can customize the appearance and behavior of the grid by using various arguments in the grid.arrange() function. For example, you can change the size and position of each plot by using the widths and heights arguments. You can also change the labels or add titles or legends using the top, bottom, left, or right arguments. For example, the following code changes the size and position of each plot and adds a title and a legend:

library(grid)
grid.arrange(p1, p2, p3, p4,
             nrow = 2,
             ncol =2, 
             widths = c(1.5, 1),
             heights = c(1, 1.5),
             top = textGrob("Four Different Plots Using ggplot2", gp = gpar(fontsize = 20, fontface = "bold")),
             right = arrangeGrob(NULL, legendGrob(p4$legend), ncol = 1))

Four different plots arranged in a grid with two rows and two columns with customized size, position, title, and legend

You can see that gridExtra changes the size and position of each plot and adds a title and a legend to the right of the grid.

The gridExtra package is useful when arranging multiple plots in a simple grid layout. However, it has some limitations when creating more complex layouts or aligning the axes or scales of different plots. For example, you cannot use gridExtra to create plots with shared axes or annotations. 

You also cannot control the spacing or margins between the plots. In these cases, you must use other methods to arrange multiple plots using ggplot2.

How to Use the cowplot Package to Create Complex Layouts with Shared Axes and Annotations?

Another way to create multiple plots using ggplot2 is to use the cowplot package. This package provides functions to create complex layouts with shared axes and annotations using the ggplot2 system. The cowplot package is based on the idea that a plot is a ggplot object that can be modified by adding or removing components.

The main function in the cowplot package is plot_grid(). This function allows you to arrange multiple plots (or other ggplot objects) in a grid layout with a specified number of rows or columns. 

For example, if you want to arrange four different plots (p1, p2, p3, and p4) in a grid with two rows and two columns, you can use plot_grid() as follows:

library(cowplot)
plot_grid(p1, p2, p3, p4, nrow = 2, ncol = 2)

Four different plots arranged in a grid with two rows and two columns using cowplot

You can see that cowplot arranges the four plots in a grid with two rows and two columns. Each plot has its axes and scales. You can also see that cowplot does not add any labels or margins to the plots.

Customize the appearance

You can customize the appearance and behavior of the grid by using various arguments in the plot_grid() function. For example, you can change the size and position of each plot by using the rel_widths and rel_heights arguments. Using the align argument, you can also align the axes or scales of different plots. For example, the following code changes the size and position of each plot and aligns the x-axes across all panels:

plot_grid(p1, p2, p3, p4,
          nrow = 2,
          ncol = 2,
          rel_widths = c(1.5, 1),
          rel_heights = c(1, 1.5),
          align = "v")

Four different plots arranged in a grid with two rows and two columns with customized size, position, and aligned x-axes using cowplot

You can see that cowplot changes the size and position of each plot and aligns the x-axes across all panels.

Add Annotations or Captions to individual Panels 

One of the advantages of cowplot is that it allows you to add annotations or captions to individual panels or the whole plot. For example, you can use the label_x and label_y arguments to add labels to each panel. You can also use the ggdraw() and draw_*() functions to add titles, legends, or other elements to the plot. For example, the following code adds labels, a title, and a legend to the grid:

p6 <- plot_grid(p1, p2, p3, p4,
                nrow = 2,
                ncol = 2,
                rel_widths = c(1.5, 1),
                rel_heights = c(1, 1.5),
                align = "v",
                label_x = c("A", "B"),
                label_y = c("C", "D"))
p6 <-ggdraw(p6) +
  draw_plot_label("Four Different Plots Using ggplot2", x = 0.1, y = 0.1, size = 20) +
  draw_plot(p4$legend, x = 0.8, y = 0.8)
p6

Four different plots arranged in a grid with two rows and two columns with customized size, position, aligned x-axes, labels, title, and legend using cowplot

You can see that cowplot adds labels (A, B, C, and D) to each panel and a title and a legend to the whole plot.

The cowplot package is useful when creating complex layouts with shared axes and annotations using ggplot2. However, it has some limitations when creating plots with different geoms or data sources. For example, you cannot use cowplot to create plots with facets or different scales. 

You also cannot control the spacing or margins between the plots. In these cases, you must use other methods to arrange multiple plots using ggplot2.

How to Use the ggpubr Package to Arrange Multiple Plots with Common Features and Themes?

Another way to create multiple plots using ggplot2 is to use the ggpubr package. This package provides functions to arrange multiple plots with common features and themes using the ggplot2 system. The ggpubr package is based on the idea that a plot is a ggplot object that can be modified by adding or removing components.

The main function in the ggpubr package is ggarrange(). This function allows you to arrange multiple plots (or other ggplot objects) in a grid layout with a specified number of rows or columns. For example, if you want to arrange four different plots (p1, p2, p3, and p4) in a grid with two rows and two columns, you can use ggarrange() as follows:

library(ggpubr)
ggarrange(p1, p2, p3, p4, nrow = 2, ncol = 2)

Four different plots arranged in a grid with two rows and two columns using ggpubr]


You can see that ggpubr arranges the four plots in a grid with two rows and two columns. Each plot has its axes and scales. You can also see that ggpubr does not add labels or margins to the plots.

You can customize the appearance and behavior of the grid by using various arguments in the ggarrange() function. For example, you can change the size and position of each plot by using the widths and heights arguments. Using the align argument, you can also align the axes or scales of different plots. For example, the following code changes the size and position of each plot and aligns the x-axes across all panels:

ggarrange(p1, p2, p3, p4,
          nrow = 2,
          ncol = 2,
          widths = c(1.5, 1),
          heights = c(1, 1.5),
          align = "v")

Four different plots arranged in a grid with two rows and two columns with customized size, position, and aligned x-axes using ggpubr

You can see that ggpubr changes the size and position of each plot and aligns the x-axes across all panels.

One of the advantages of ggpubr is that it allows you to add common features and themes to multiple plots. For example, you can use the common.legend argument to add a common legend to all plots. You can also use the annotate_figure() function to add labels, titles, captions, or other elements to the whole figure. For example, the following code adds a common legend and a title to the grid:

p7 <- ggarrange(p1, p2, p3, p4,
                nrow = 2,
                ncol = 2,
                widths = c(1.5, 1),
                heights = c(1, 1.5),
                align = "v",
                common.legend = TRUE)
p7 <- annotate_figure(p7,
                      top = text_grob("Four Different Plots Using ggplot2", size = 20))
p7

Four different plots arranged in a grid with two rows and two columns with customized size, position, aligned x-axes, common legend, and title using ggpubr

You can see that ggpubr adds a common legend to the bottom right corner of the grid and a title to the top of the figure.

The ggpubr package is useful when creating multiple plots with common features and themes using ggplot2. However, it has some limitations when creating plots with different geoms or data sources. For example, you cannot use ggpubr to create plots with facets or different scales. You also cannot control the spacing or margins between the plots. In these cases, you must use other methods to arrange multiple plots using ggplot2.

Conclusion

In this article, I have shown you how to produce multiple plots using ggplot2 and arrange them on a single page or multiple pages. You have learned to use different packages and functions to combine multiple ggplots in various layouts, such as grid, facet, or custom. You have also learned how to align the plot panels, add captions and annotations, and export the arranged plots to a file.

Here are some key points to remember:

  • To create multiple panels within one plot based on one or more factors, you can use one of the faceting functions: facet_wrap() or facet_grid().
  • To arrange multiple plots in a simple grid layout using the grid system, you can use the gridExtra package and the grid.arrange() function.
  • To create complex layouts with shared axes and annotations using the ggplot2 system, you can use the cowplot package and the plot_grid() function.
  • To arrange multiple plots with common features and themes using the ggplot2 system, you can use the ggpubr package and the ggarrange() function.

This article has helped you to create more complex and informative visualizations using ggplot2. 

FAQs

What is the difference between facet_wrap() and facet_grid()?

Both functions create multiple panels within one plot based on one or more factors. However, facet_wrap() wraps the panels into a rectangular layout with a single row or column while facet_grid() creates a grid of panels with two rows or columns.

What is the difference between grid.arrange() and plot_grid()?

Both functions arrange multiple plots in a grid layout with a specified number of rows or columns. However, grid.arrange() uses the grid system, while plot_grid() uses the ggplot2 system. This means that grid.arrange() you can arrange any grid objects while plot_grid() only arranging ggplot objects.

It also means that plot_grid() it can align the axes or scales of different plots, while grid.arrange() it cannot.

What is the difference between plot_grid() and ggarrange()?

Both functions arrange multiple plots in a grid layout with a specified number of rows or columns using the ggplot2 system. However, ggarrange() can add common features and themes to multiple plots, such as a common legend, title, caption, or annotation. It can also arrange multiple plots over multiple pages.

How can I export the arranged plots to a file?

You can use the ggsave() function to export the arranged plots to a file in various formats, such as PDF, PNG, JPEG, or SVG. You need to specify the filename, the plot object, and the width and height of the output file. The file will be saved on the working directory; read more: How to Set Working Directory setwd in R. For example, the following code exports the plot object p7 to a PDF file named “plots.pdf” with a width of 10 inches and a height of 8 inches:

ggsave("plots.pdf", p7, width = 10, height = 8)

How can I customize the appearance and behavior of the arranged plots?

You can use various arguments in each function to customize the appearance and behavior of the arranged plots. For example, you can change the size and position of each plot by using the widths, heights, rel_widths, or rel_heights arguments. You can also change the alignment of the axes or scales by using the align or scales arguments. You can also add labels, titles, captions, legends, or other elements using  label_x, label_y, top, bottom, left, right, common.legend, or annotate_figure() arguments.

Can ggplot2 have multiple plots in the same figure?

Yes, ggplot2 can have multiple plots in the same figure. You can use different functions and packages to arrange multiple ggplots in various layouts, such as grid, facet, or custom. Some of the functions and packages are `grid.arrange()` [gridExtra package], `plot_grid()` [cowplot package], `ggarrange()` [ggpubr package], and `facet_wrap()` or `facet_grid()` [ggplot2 package]. 

How do I create a multipanel figure in R?

A multipanel figure is a figure that contains more than one plot or graph on the same page. There are different ways to create a multipanel figure in R, depending on the type and layout of the plots you want to arrange. Some of the common methods are:
  • Using the `ggplot2` package creates plots with a consistent theme and style. You can use different functions and packages to arrange multiple ggplots in various layouts, such as grid, facet, or custom. Some of the functions and packages are `grid.arrange()` [gridExtra package], `plot_grid()` [cowplot package], `ggarrange()` [ggpubr package], and `facet_wrap()` or `facet_grid()` [ggplot2 package].
  • Using the `par()` function to set the graphical parameters for the number of rows and columns of plots, such as `par(mfrow = c(2, 2))` for a 2 by 2 layout. Then, you can use the base R plotting functions (such as `plot()`, `hist()`, or `boxplot()`) to create the plots in each panel.

Which function from the ggplot2 package allows for splitting a single graph into multiple grids?

One of the functions from the ggplot2 package that allows the split of a single graph into multiple grids is `facet_grid()`. This function creates a grid of panels based on two factors. Each panel shows a subset of the data with its axes and scales.

Which function is used to draw multiple plots in one figure?

Many functions can be used to draw multiple plots in one figure in R. Some of them are:

  • `par()` from base R
  • `grid.arrange()` from gridExtra package
  • `plot_grid()` from cowplot package
  • `ggarrange()` from ggpubr package

These functions allow you to arrange multiple plots (or other graphical objects) in a grid layout with a specified number of rows or columns. You can also customize the appearance and behavior of the grid by using various arguments in each function. 

Is ggplot2 the only way to create plots in R?

No, ggplot2 is not the only way to create plots in R. There are other ways to create plots in R, such as:

  • Using base R plotting functions (such as `plot()`, `hist()`, or `boxplot()`) that provide basic graphics capabilities
  • Using lattice package that provides high-level graphics functions based on Trellis graphics
  • Using other specialized packages that provide specific types of plots (such as maps, networks, or interactive graphics)

However, ggplot2 is one of the most popular and powerful packages for creating plots in R. It implements the grammar of graphics, which allows you to create graphs by specifying the components and layers of your plot. It also provides a consistent theme and style for your plots. 

Can you make figures in R?

Yes, you can make figures in R. A figure is a graphical representation of data or information that can include one or more plots or graphs. There are different ways to make figures in R, such as:

  • Using base R plotting functions (such as `plot()`, `hist()`, or `boxplot()`) that provide basic graphics capabilities
  • Using ggplot2 package that provides high-level graphics functions based on the grammar of graphics
  • Using other packages that provide specific types of plots (such as maps, networks, or interactive graphics)

You can also combine multiple plots in one figure using different functions and packages, such as `par()` [base R], `grid.arrange()` [gridExtra package], `plot_grid()` [cowplot package], or `ggarrange()` [ggpubr package]. You can also customize the appearance and behavior of the figure by using various arguments and options in each function or package. 

How to use the par function in R?

The par function in R is used to set or query the graphical parameters for the current device. Graphical parameters are settings that affect the appearance and behavior of the plots or graphs, such as the size, color, font, margin, or layout of the graphical elements. You can use the par function to set the graphical parameters before creating a plot or graph or to query the current values of the graphical parameters.

The par function takes one or more named arguments that specify the graphical parameters to be set or queried. For example, the following code sets the number of rows and columns of plots to be 2 by 2, the margin size to be 0.5 inches on each side, and the background color to be light blue:

par(mfrow = c(2, 2), mai = c(0.5, 0.5, 0.5, 0.5), bg = "lightblue")

The par function returns a list of the previous values of the graphical parameters changed by the function call. You can use this list to restore the previous values of the graphical parameters by passing it to another par function call. 

For example, the following code saves the previous values of the graphical parameters in a variable called oldpar, sets some new values for the graphical parameters, and then restores the old values:

oldpar <- par(mfrow = c(2, 2), mai = c(0.5, 0.5, 0.5, 0.5), bg = "lightblue")
# Create some plots here
par(oldpar)

You can also use the par function without any arguments to query all the current values of the graphical parameters. For example, the following code prints a list of all the current values of the graphical parameters:

par()

Does par work with ggplot?

No, par does not work with ggplot. The par function sets or queries the graphical parameters for the base R plotting system, which differs from the ggplot2 plotting system. The ggplot2 plotting system is based on the grammar of graphics, which allows you to create graphs by specifying the components and layers of your plot. The ggplot2 plotting system also provides a consistent theme and style for your plots.

To customize the appearance and behavior of your ggplots, you need to use different functions and options from ggplot2 or other related packages. For example, you can use:

  • The `theme()` function or one of the predefined themes (such as `theme_bw()`, `theme_classic()`, or `theme_minimal()`) to modify the appearance of your plot
  • The `scale_*()` functions to modify the axes or legends of your plot
  • The `coord_*()` functions to modify the coordinates or aspect ratio of your plot
  • The `facet_*()` functions to create multiple panels within one plot based on one or more factors

What is the difference between facet_wrap and facet_grid?

Both functions create multiple panels within one plot based on one or more factors. However, facet_wrap wraps the panels into a rectangular layout with a single row or column, while facet_grid creates a grid of panels with two rows or columns.

The difference between facet_wrap and facet_grid is mainly in how they arrange the panels based on the factors. For example, if you have a factor with three levels (A, B, and C), facet_wrap will arrange the panels as follows:

| A | B | C |

while facet_grid will arrange the panels as follows:

| A | | B | | C |

You can also specify two factors for facet_grid to create a grid of panels based on their combinations. For example, if you have another factor with two levels (X and Y), facet_grid will arrange the panels as follows:

X Y
A A
B B
C C

You cannot specify two factors for facet_wrap. However, you can use a formula to combine two factors into one factor. For example, if you use ~ X + Y as the formula for facet_wrap, it will arrange the panels as follows:

| AX | AY | BX | BY | CX | CY |

You can also customize the appearance and behavior of the facets by using various arguments in each function. For example, you can change the number of rows or columns of panels by using the nrow or ncol arguments for facet_wrap or the layout argument for facet_grid. You can also change the direction of the panels by using the dir argument for facet_wrap or swap the rows and columns by using a formula like . ~ factor for facet_grid.

Join Our Community   Allow us to Assist You 

About the Author

Ph.D. Scholar | Certified Data Analyst | Blogger | Completed 5000+ data projects | Passionate about unravelling insights through data.

Post a Comment

RStudiodataLab Chatbot
Have A Question?We will reply within minutes
Hello, how can we help you?
Start chat...
Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.