Lab 3: Adding Layers with ggplot2 and Data Preparation

Visualizing mtcars, Wrangling Tidy Data, and Simple Predictions

Author

Write your name here

Learning goals

By the end of this lab, you should be able to:

  1. Prepare and recode variables using modern dplyr pipelines (%>% and |>).
  2. Build a ggplot2 chart one layer at a time, including faceting.
  3. Build and label a scatter plot that compares different car metrics.

1. Load the Tidyverse and Inspect the Data

We will use the built-in mtcars dataset. First, load tidyverse, which includes both dplyr (for data manipulation) and ggplot2 (for visualization).

library(tidyverse)

head(mtcars)
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

We will focus on:

  • wt: weight, in 1,000 pounds
  • mpg: miles per gallon
  • am: transmission type (0 = automatic, 1 = manual)
  • cyl: number of cylinders (4, 6, or 8)

2. Data Management: Cleaning and Labeling Variables

Instead of transforming data types inside our plotting code, good data-management practice means preparing our dataset explicitly first. We will convert numeric codes into informative factors.

This lab uses %>% for its dplyr pipelines. The base R pipe, |>, moves data from the left side into the function on the right in the same general way.

mtcars_clean <- mtcars %>%
  mutate(
    transmission = factor(am, levels = c(0, 1), labels = c("Automatic", "Manual")),
    cylinders = factor(cyl)
  )

glimpse(mtcars_clean)
Rows: 32
Columns: 13
$ mpg          <dbl> 21.0, 21.0, 22.8, 21.4, 18.7, 18.1, 14.3, 24.4, 22.8, 19.…
$ cyl          <dbl> 6, 6, 4, 6, 8, 6, 8, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 4, 4, …
$ disp         <dbl> 160.0, 160.0, 108.0, 258.0, 360.0, 225.0, 360.0, 146.7, 1…
$ hp           <dbl> 110, 110, 93, 110, 175, 105, 245, 62, 95, 123, 123, 180, …
$ drat         <dbl> 3.90, 3.90, 3.85, 3.08, 3.15, 2.76, 3.21, 3.69, 3.92, 3.9…
$ wt           <dbl> 2.620, 2.875, 2.320, 3.215, 3.440, 3.460, 3.570, 3.190, 3…
$ qsec         <dbl> 16.46, 17.02, 18.61, 19.44, 17.02, 20.22, 15.84, 20.00, 2…
$ vs           <dbl> 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, …
$ am           <dbl> 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, …
$ gear         <dbl> 4, 4, 4, 3, 3, 3, 3, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 4, 4, …
$ carb         <dbl> 4, 4, 1, 1, 2, 1, 4, 2, 2, 4, 4, 3, 3, 3, 4, 4, 4, 1, 2, …
$ transmission <fct> Manual, Manual, Manual, Automatic, Automatic, Automatic, …
$ cylinders    <fct> 6, 6, 4, 6, 8, 6, 8, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 4, 4, …

3. Build a Plot Layer by Layer

Step 3a: Initialize the Canvas

ggplot() defines the dataset and basic visual mapping using aes().

ggplot(mtcars_clean, aes(x = wt, y = mpg))

Step 3b: Add Data Points and Color

We use + to add geom_point(). Mapping color = transmission uses our newly cleaned factor variable.

ggplot(mtcars_clean, aes(x = wt, y = mpg, color = transmission)) +
  geom_point(size = 3)

Step 3c: Add Trend Lines and Labels

geom_smooth() adds linear trend lines (method = "lm"). labs() updates the title and axis labels.

ggplot(mtcars_clean, aes(x = wt, y = mpg, color = transmission)) +
  geom_point(size = 3) +
  geom_smooth(method = "lm", se = FALSE) +
  labs(
    title = "Fuel Efficiency vs. Car Weight",
    subtitle = "Comparing Automatic and Manual Transmissions",
    x = "Weight (1,000 lbs)",
    y = "Miles Per Gallon (MPG)",
    color = "Transmission Type"
  ) +
  theme_minimal()

4. Multi-Panel Visualizations (Faceting)

To avoid visual clutter when comparing subgroups, we can split plots into side-by-side panels using facet_wrap().

ggplot(mtcars_clean, aes(x = wt, y = mpg, color = transmission)) +
  geom_point(size = 3) +
  geom_smooth(method = "lm", se = FALSE) +
  facet_wrap(~ cylinders) +
  labs(
    title = "Fuel Efficiency vs. Weight Faceted by Engine Cylinders",
    x = "Weight (1,000 lbs)",
    y = "Miles Per Gallon (MPG)",
    color = "Transmission"
  ) +
  theme_minimal()

5. Practice: Build and Label Your Own Plot

Now create your own plot using mtcars_clean. Choose two numeric car metrics to compare. You may use:

  • mpg: miles per gallon
  • wt: weight, in 1,000 pounds
  • hp: horsepower
  • disp: engine displacement
  • qsec: time to complete one-quarter mile

Add a point for each car and label each point with its number of cylinders. Put label = cylinders inside aes() in geom_text(). Use labs() to give your chart a clear title, axis labels, and a legend label for the number of cylinders.

# Choose two numeric variables for x and y.
# Add geom_point() and geom_text(aes(label = cylinders)).
# Use labs() to explain your chart clearly.
library(ggplot2)

ggplot(mtcars_clean, aes(x = wt, y = mpg, color = factor(cylinders))) +
  geom_point(size = 3) +
  geom_text(
    aes(label = cylinders),
    vjust = -0.7,
    show.legend = FALSE
  ) +
  labs(
    title = "Car Weight vs. Miles per Gallon",
    x = "Weight (1,000 pounds)",
    y = "Miles per Gallon (MPG)",
    color = "Number of Cylinders"
  )

Reflection Questions

  1. Which two car metrics did you compare, and what pattern do you see in your plot? The figure shows a general pattern: heavier cars tend to consume more fuel.

  2. How do the cylinder labels help you interpret the points? The cylinder labels display the engigine size.

  3. What layer did you add last, and what did it change in the chart?