library("patchwork")Warning: package 'patchwork' was built under R version 4.6.1
The patchwork package allows you to combine multiple ggplots into one graphic.
It is a separate package to tidyverse and requires installing. The install instructions are in the below link.
Once installed you can load the library.
For demonstration we’ll load the mushroom_tbl data from the mgrtibbles package (hyperlink includes install instructions). For easier plot visualisation we’ll subsample the data.
Warning: package 'reactable' was built under R version 4.6.1
To create a patchwork we need a few ggplots saved as objects first.
#Bar chart
barchart <- mushroom_tbl |>
ggplot2::ggplot(aes(x = class)) +
ggplot2::geom_bar()
#Histogram
histogram <- mushroom_tbl |>
ggplot2::ggplot(aes(x = cap_diameter)) +
ggplot2::geom_histogram()
#Line graph
line <- mushroom_tbl |>
ggplot2::ggplot(aes(x = stem_width, y = stem_height)) +
ggplot2::geom_line()
#Scatter plot
point <- mushroom_tbl |>
ggplot2::ggplot(aes(x = stem_width, y = stem_height)) +
ggplot2::geom_point()
#Box plot
box <- mushroom_tbl |>
ggplot2::ggplot(aes(x = class, y = cap_diameter)) +
ggplot2::geom_boxplot()To create a graphic with plots side by side you can use |.
The below code creates a graphic with the line and point ggplots side by side.
To put one plot on top of another in a graphic you can use /
The below code creates a graphic with the barchart above the histogram.
A more complicated graphic can be created by mixing the use of | and /. If doing this it is common to put all the plots in the same row in brackets ().
Example code and plot below.
You can save a patchworked graphic with ggsave()
`stat_bin()` using `bins = 30`. Pick better value `binwidth`.
The PNG file contains the following image:
As you may have noticed when laying out the plots on a graphic patchwork will divide spaces equally between the rows and the columns within each row. In the last plot:
There are many ways to control the layout. To see these various methods please check the following link: