Week 4: Data Visualization with ggplot2

GPH-GU 2182: Statistical Programming in R · Fall 2026

Yang Feng, PhD

New York University · School of Global Public Health

2026-09-23

Welcome to Week 4!

Today's Roadmap

  1. The Grammar of Graphics: Data, aesthetics, geometries.
  2. Visualizing Distributions: Histograms, densities, boxplots.
  3. Small Multiples & Trends: Faceting & smooth curves.
  4. Publication Polish: Scales, viridis palettes, themes.
  5. AI Corner: Spotting misleading axes and chartjunk.

Today's Milestones

  • Homework 4: Released today (ggplot2 visualization).
  • Looking Ahead: Quiz 2 takes place next week in Week 5.

Cycle 1: The Grammar of Graphics

Why ggplot2?

Created by Hadley Wickham based on Leland Wilkinson's The Grammar of Graphics.

  • Declarative System: You describe what you want to see, not low-level drawing steps.
  • Layered Composition: Stack data, aesthetics, geometries, facets, and themes using +.
  • Publication Standard: Automatic legends, consistent scales, and reproducible output.

Base R vs. ggplot2

Base R (plot())

  • Fast for quick disposable sketches.
  • Pen-on-paper model (cannot easily modify earlier layers).
  • Hard to build multi-panel legends or faceting.

ggplot2 (library(ggplot2))

  • Object-oriented: store plots in variables (p <- ggplot(...)).
  • Effortless layering and faceting.
  • Standard across biomedical and epidemiology research.

The 3 Core Components of Every Plot

\[\text{Plot} = \text{Data} + \text{Aesthetic Mappings} + \text{Geometric Layers}\]

ggplot(data = <DATA>, mapping = aes(<MAPPINGS>)) +
  <GEOM_FUNCTION>()
  1. Data: A data.frame or tibble.
  2. Aesthetics (aes()): Visual channels (\(x\), \(y\), color, size, shape, alpha).
  3. Geometries (geom_*()): Visual representation (points, lines, bars, boxes).

Building a Scatterplot: Step-by-Step

library(ggplot2)

# Data + aesthetics, but no geometry yet
p <- ggplot(data = airquality, aes(x = Temp, y = Ozone))
p

p + geom_point()

p + geom_point(aes(color = factor(Month)), size = 2.5, alpha = 0.8)

Aesthetic Mapping vs. Setting Constants

Mapping Inside aes()

Connects a visual channel to a variable in your data:

# Color varies by Month
p + geom_point(aes(color = factor(Month)))

Setting Outside aes()

Sets a fixed constant for all observations:

# All points are navy and size 3
p + geom_point(color = "navy", size = 3, alpha = 0.7)

Tip

Never put a fixed value inside aes(): aes(color = "blue") makes R treat "blue" as a one-level factor.

Mapping vs. Setting: The Result

Mapped: color by Month

Set: one navy color

👥 Paired Exercise 1: Air Quality Scatterplot (10 min)

Task

In your week-04-inclass.qmd worksheet:

  1. Use the built-in airquality dataset.
  2. Create a scatterplot of Solar Radiation (Solar.R, \(x\)) vs Ozone (Ozone, \(y\)).
  3. Map Wind Speed (Wind) to the color aesthetic.
  4. Set point transparency alpha = 0.7 and size = 3 (outside aes).
  5. Add a smooth trendline using geom_smooth(method = "loess", color = "darkblue").

Key Observation

  • High solar radiation paired with low wind velocity correlates strongly with peak ozone pollution episodes.

Cycle 2: Visualizing Distributions

Histograms (geom_histogram)

Visualizing a single continuous variable:

ggplot(airquality, aes(x = Temp)) +
  geom_histogram(binwidth = 5, fill = "#3498db", color = "white") +
  labs(x = "Temperature (°F)", y = "Count")

  • Always test multiple binwidth values to avoid hiding peaks or creating artificial noise.

Density Curves (geom_density)

Smooth probability density estimates:

ggplot(airquality, aes(x = Temp, fill = factor(Month))) +
  geom_density(alpha = 0.4) +
  labs(x = "Temperature (°F)", y = "Density", fill = "Month")

  • Use alpha = 0.4 so overlapping sub-populations remain visible.

Boxplots (geom_boxplot)

Comparing distributions across categorical groups:

ggplot(airquality, aes(x = factor(Month), y = Ozone, fill = factor(Month))) +
  geom_boxplot(outlier.shape = 1, alpha = 0.7) +
  labs(x = "Month", y = "Ozone (ppb)")

  • Displays 5-number summary (Min, Q1, Median, Q3, Max) + outlier flags.

Boxplot + Jitter Overlay (geom_jitter)

Layering raw observations over boxplots reveals sample sizes and local clusters:

ggplot(airquality, aes(x = factor(Month), y = Ozone, fill = factor(Month))) +
  geom_boxplot(outlier.shape = NA, alpha = 0.7) +
  geom_jitter(width = 0.2, alpha = 0.5, color = "black")

  • Set outlier.shape = NA on the boxplot to prevent plotting outliers twice!

Discrete Counts: geom_bar vs. geom_col

geom_bar() (Counts Rows)

When R calculates frequency for you:

# Data has raw individual rows
ggplot(airquality, aes(x = factor(Month))) +
  geom_bar(fill = "steelblue")

geom_col() (Pre-Summarized)

When data already has a numeric height column:

summary_df <- data.frame(
  region = c("North", "South", "West"),
  admissions = c(120, 340, 210))
ggplot(summary_df, aes(x = region, y = admissions)) +
  geom_col(fill = "darkgreen")

geom_bar vs. geom_col: The Result

geom_bar(): R counts the rows

geom_col(): you supply the heights

👥 Paired Exercise 2: Comparing Ozone by Month (10 min)

Task

In week-04-inclass.qmd:

  1. Build a violin plot comparing Ozone across Months (x = factor(Month), y = Ozone).
  2. Fill violins by factor(Month) with alpha = 0.5.
  3. Overlay a narrow boxplot (width = 0.2, fill = "white") inside each violin.

Pro-Tip

Layer order matters! Put geom_violin() first, then geom_boxplot() on top so the boxplot sits cleanly inside the violin body.

Cycle 3: Small Multiples & Trendlines

Faceting with facet_wrap

Split complex multi-group data into clean sub-panels:

ggplot(airquality, aes(x = Temp, y = Ozone)) +
  geom_point(color = "navy", alpha = 0.7) +
  geom_smooth(method = "lm", se = FALSE, color = "red") +
  facet_wrap(~ Month, nrow = 1)

  • nrow = 1 aligns all panels in a single horizontal strip.

Controlling Facet Scales

By default, all subplots share the exact same axis limits (scales = "fixed"). Use scales = "free_y" for independent y-axes, or scales = "free" for fully independent axes:

ggplot(airquality, aes(x = Temp, y = Ozone)) +
  geom_point(color = "navy", alpha = 0.7) +
  facet_wrap(~ Month, nrow = 1, scales = "free_y")

Free y-Scales: The Result

Note

Use fixed scales when comparing absolute quantities; use free scales when comparing internal distribution shapes.

Cycle 4: Polishing Publication Graphics

Informative Labels: labs()

Never leave raw column names on a presentation or report figure:

p_pub <- ggplot(airquality, aes(x = Temp, y = Ozone, color = Wind)) +
  geom_point(size = 3, alpha = 0.8) +
  geom_smooth(method = "lm", color = "black", linetype = "dashed", se = FALSE) +
  labs(
    title = "Air Pollution Dynamics at LaGuardia Airport",
    subtitle = "Daily Ozone, Temperature, and Wind (May - Sep 1973)",
    x = "Maximum Daily Temperature (°F)",
    y = "Mean Ozone (ppb)",
    color = "Wind Speed\n(mph)",
    caption = "Source: NYS Department of Environmental Conservation"
  )
p_pub

Informative Labels: labs()

Colorblind-Safe Scales & Themes

Viridis Palettes

p_pub +
  scale_color_viridis_c(option = "viridis")

  • Perceptually uniform and legible in grayscale.

Clean Themes

p_pub +
  scale_color_viridis_c(option = "viridis") +
  theme_minimal(base_size = 12) +
  theme(legend.position = "bottom")

Saving Figures: ggsave()

Save vector or high-resolution raster images for publications and reports:

ggsave(
  filename = "figures/figure1_ozone.png",
  plot = p_pub,
  width = 8,
  height = 5,
  dpi = 300
)

AI Corner: Misleading Visuals & Baselines

Spotting Truncated Baselines

❌ AI Prompt: “Bar chart of mortality rate”

df <- data.frame(year = 2019:2023,
  rate = c(49.8, 50.1, 50.4, 50.2, 50.9))
ggplot(df, aes(x = year, y = rate)) +
  geom_col() +
  coord_cartesian(ylim = c(48, 52))

✅ The Verified Rule

# Same data, honest baseline at 0
ggplot(df, aes(x = year, y = rate)) +
  geom_col()

Truncated vs. Honest Baseline

❌ Axis starts at 48

  • A truncated \(y\)-axis makes a 2% change look like a surge!

✅ Axis starts at 0

  • Bars must start at 0 (geom_col, geom_bar).
  • Overplotting: geom_jitter(), alpha < 0.5, or 2D density.
  • Color: colorblind-friendly scales (viridis).

Wrap-Up & Next Steps

Today's Key Takeaways

  1. Grammar of Graphics: Data + aes() + geom_*().
  2. Right geoms for continuous vs. discrete health variables.
  3. Multi-panel small multiples with facet_wrap().
  4. Professional polish with labs(), theme_minimal(), and viridis.

Looking Ahead to Week 5

  • Homework 4: Released today.
  • Next Week: Data Wrangling with dplyr & Pipes (filter, mutate, select, arrange).
  • 📝 Quiz 2 (Weeks 3–4): In the last 30 minutes of Week 5!