Day 19 of viz with me

Data viz Beginner ggplot patchwork DataViz Challenge

Combining plots.

Soundarya Soundararajan true
2024-10-19

Welcome to Day 19!

Goals for today: We will learn how to combine plots easily in R.

We’ll achieve this using the patchwork library, which allows us to arrange multiple plots in a simple and intuitive way.

Patchwork to Combine Plots

Let’s start with two plots using the palmerpenguins dataset: a scatter plot and a box plot.

library(tidyverse)
library(palmerpenguins)
# Scatter plot using palmerpenguins data
p1 <- penguins %>% 
  ggplot(aes(x = flipper_length_mm, y = body_mass_g)) +
  geom_point()

# Box plot using palmerpenguins data
p2 <- penguins %>% 
  ggplot(aes(x = species, y = body_mass_g)) +
  geom_boxplot()

Now, we can combine these two plots using patchwork.

Combining side-by-side

library(patchwork)
p1 + p2

Stacking vertically

If you want to stack the plots on top of each other, use the / operator:

p1 / p2

This works nicely even for more than two plots. You can combine multiple plots in a single row or column using the + and / operators.

That’s it for today! Tomorrow, we’ll dive into some exercises to practice this. See you then!

Citation

For attribution, please cite this work as

Soundararajan (2024, Oct. 19). My R Space: Day 19 of viz with me. Retrieved from https://github.com/soundarya24/SoundBlog/posts/2024-10-18-day-19-of-viz-with-me/

BibTeX citation

@misc{soundararajan2024day,
  author = {Soundararajan, Soundarya},
  title = {My R Space: Day 19 of viz with me},
  url = {https://github.com/soundarya24/SoundBlog/posts/2024-10-18-day-19-of-viz-with-me/},
  year = {2024}
}