Objectives and Concepts

  • Practice basic plotting skills in R
  • Create multi-panel figures

Data

We’ll use the palmerpenguins data for this exercise.

Example

It’s pretty straightforward to make simple multi-panel plot in R using the par() function.

To begin, I’ll create two simple plots form the penguins data, then combine them into a single figure.

Simple plots

I’ll make a scatterplot of penguin flipper length and body mass:

plot(
  flipper_length_mm ~ body_mass_g, data = penguins,
  main = "Mike's Beautiful\nScatterplot",
  xlab = "Body Mass (g)",
  ylab = "Flipper Length (mm)")

Next, I’ll make a conditional boxplot of body mass conditioned on species:

boxplot(
  body_mass_g ~ species, data = penguins,
  main = "Mike's Awesome\nConditional Boxplot",
  xlab = "Penguin Species",
  ylab = "Body Mass (g)")

The par() function

It’s super easy to make gridded multi-panel plots.

You can simply use the function par() with the mfrow argument.

The mfrow argument expects a vector of two numbers:

  • The first number specifies the number of rows in your plot grid.
  • The second number is the number of columns.

I can combine my plots above into a 1-row, 2-column grid by inserting a call to par() before my plotting code:

# specify a grid with 1 row, 2 columns
par(mfrow = c(1, 2))

# First plot
plot(
  flipper_length_mm ~ body_mass_g, data = penguins,
  main = "Mike's Lovely\nScatterplot",
  xlab = "Body Mass (g)",
  ylab = "Flipper Length (mm)")

# Second plot
boxplot(
  body_mass_g ~ species, data = penguins,
  main = "Mike's Awesome\nConditional Boxplot",
  xlab = "Penguin Species",
  ylab = "Body Mass (g)")

How could you create a 2 by 2 grid of plots?

Instructions

So far in the course, we’ve created histograms using hist(), simple and conditional boxplots using boxplot(), and scatterplots using plot(). Now we’ll learn how to combine several individual plots into a single multi-panel figure.

  1. Create a new RMarkdown document. Create a first-level header called “Group Members”. Write down everybody’s names in this section.
  2. Create a new section and code chunk. Load the palmerpenguins package.
    • Do you remember how to load a package?
  3. Create a new section and code chunk in which you’ll make four individual single-panel plots. Your plots can be histograms, boxplots, or scatterplots. Feel free to use any of the columns in penguins that you like.
  4. Create a new section and code chunk in which you make a 2 by 2 grid of plots. Use the four individual plots from step 3.

Report

Submit a document that includes the following sections

  1. Group members’ names
  2. Loading the penguins data.
  3. Four individual plots. These must have custom axis labels and titles.
  4. One multi-panel plot created from your four individual plots.