---
title: "Week 1 Lecture 1"
subtitle: "Why we visualize data"
author: "Shannon Gallagher"
date: "August 24, 2026"
date-format: long
format:
  revealjs:
    theme: ../mads-36613-assignments/lecture_drafts/theme.scss
    slide-number: c/t
    chalkboard: true
    code-fold: show
    code-line-numbers: true
    smaller: true
    linestretch: 1.25
    df-print: paged
    fig-width: 8
    fig-height: 4.5
    footer: "MaDS Data Visualization · Week 1"
execute:
  echo: true
  warning: false
  message: false
---

```{r setup}
#| include: false
library(readr)
library(dplyr)
library(stringr)
library(tidyr)
library(forcats)
library(lubridate)
library(ggplot2)
library(scales)

theme_set(theme_minimal(base_size = 14))
gold <- "#d99a00"
deep_gold <- "#9b6b00"
charcoal <- "#2f2a1f"
```

## About me

Special Faculty and Lecturer, Carnegie Mellon Statistics & Data Science

- Research: statistical machine learning, evaluation, and interpretable AI; previously biostats!
- Dabble in sports statistics
- Office: Baker Hall 129D
- Office hours: Monday 11:00 a.m.–noon and Tuesday 1:00–2:00 p.m.

## We visualize data to gain insights

::: {.incremental}
- To **check** the data — outliers, clusters, gaps, and data-quality problems.
- To **find** structure that summaries hide — trends, nonlinearity, interactions.
- To **compare** groups on a common scale.
- To **communicate** a finding to someone who will not read your code.
- To **utilize** human expertise
:::

. . .

Two datasets can share nearly identical means, standard deviations, and
correlations—and look nothing alike.

. . .

::: {.callout}
Always visualize your data before analyzing it.
:::

## Same summaries. Different data.

```{r anscombe-quartet}
#| echo: false
#| fig-alt: "Anscombe's quartet shown as four scatterplots with the same fitted regression line but very different patterns: linear, curved, one vertical outlier, and one high-leverage point."
#| fig-height: 4.8
#| fig-width: 8

anscombe_long <- bind_rows(lapply(1:4, function(i) {
  tibble(
    dataset = paste("Dataset", i),
    x = anscombe[[paste0("x", i)]],
    y = anscombe[[paste0("y", i)]]
  )
}))

ggplot(anscombe_long, aes(x, y)) +
  geom_smooth(method = "lm", formula = y ~ x, se = FALSE,
              color = charcoal, linewidth = 0.7) +
  geom_point(color = deep_gold, size = 2.3) +
  facet_wrap(~dataset, ncol = 2) +
  coord_cartesian(xlim = c(3, 20), ylim = c(3, 13)) +
  labs(
    subtitle = "All four (rounded): x̄ = 9.00, ȳ = 7.50, sₓ = 3.32, sᵧ = 2.03, r = 0.82",
    x = "x",
    y = "y",
    caption = "Anscombe's quartet (1973) · Adapted from Ron Yurko's Week 1 course materials"
  ) +
  theme(
    strip.text = element_text(face = "bold"),
    plot.subtitle = element_text(size = 11),
    plot.caption = element_text(size = 8)
  )
```

## Course Structure

**Lectures on Mondays and Wednesdays**

- examples, code, and discussion during class,
- slides and supporting materials on the course site,
- four homework assignments,
- occasional checkpoints and two Piazza critiques,
- one final visual report.

## Opening week

- **Monday, August 24:** remote class at the scheduled time
- **Wednesday, August 26:** asynchronous recorded lecture with a **graded checkpoint**
- **Sunday, August 23:** Homework 1 opens
- **Tuesday, September 1:** Homework 1 is due at 11:59 p.m.

::: {.callout}
**Before Wednesday:** work through
[Lab 0 · Getting R, RStudio, and Quarto running](../resources/getting-started.html).
About 20 minutes, not graded.  Any questions about it can be posted to Piazza.
:::

## Course Objectives

**Work with tidy data and reproducible workflows.**

**Create high-quality statistical graphics.**

**Critique and write about visualizations.**

**Use visual evidence to support a clear recommendation.**

## Definition of Tidy Data:

- Each variable is a column.
- Each observation is a row.
- Each value is a cell.

Our running example is the **NOAA Storm Events Database**.

```{r load}
data_url <- paste0(
  "https://stat.cmu.edu/~sgallagh/courses/mads-fall-2026/",
  "datavis-36613/data/noaa_storm_events_2024_clean.csv.gz"
)
events <- read_csv(data_url, show_col_types = FALSE)
```

## What does one row represent?

```{r first-look}
events |>
  select(begin_dt, state, county_zone_name, event_type,
         damage_property_raw, deaths_direct) |>
  slice_head(n = 6)
```

One row is an **event report**—not one storm system, one county, one day, or one
insurance claim.

## Checkpoint 1 · Name the row {.smaller}

::: {.checkpoint}
Choose one NOAA column. Explain what one value means and name one conclusion that would
be invalid if you misunderstood the observational unit.
:::

**One NOAA event report**

```{r checkpoint1-row}
#| echo: false
events |>
  select(begin_dt, state, county_zone_name, event_type,
         damage_property_raw, deaths_direct) |>
  slice_head(n = 1) |>
  mutate(begin_dt = format(begin_dt, "%b %d, %Y %H:%M")) |>
  knitr::kable()
```

## A tidy table can still need cleaning {.smaller}

```{r damage-problem}
events |>
  count(damage_property_raw, sort = TRUE) |>
  slice_head(n = 5)
```

NOAA publishes damage amounts as character strings with suffixes. The course file keeps
both the raw field and a parsed dollar value.

## [The Grammar of Graphics](https://link.springer.com/book/10.1007/0-387-28695-0)

A graphic combines:

1. **data**,
2. **geometries**,
3. **aesthetic mappings**,
4. **scales**,
5. **statistical transformations**,
6. **facets**,
7. **coordinate systems**.

## Start with the `data`

```{r start-data}
type_counts <- events |>
  count(event_type, sort = TRUE) |>
  slice_head(n = 10)

ggplot(type_counts)
```

The data alone do not tell `ggplot2` what to draw.

## Need to add geometric objects!

```{r add-geom}
ggplot(type_counts, aes(x = n, y = event_type)) +
  geom_col()
```

The geometry is a bar. The columns are mapped to x- and y-position.

## Order categories for comparison

```{r order-bars}
type_counts |>
  mutate(event_type = fct_reorder(event_type, n)) |>
  ggplot(aes(x = n, y = event_type)) +
  geom_col()
```

Ordering turns an unordered list into a visible ranking.

## Modify scale, add statistical summary, and so on...

```{r polished-bar, fig.alt="Horizontal bar chart of the ten most common NOAA storm event types in 2024."}
#| output-location: slide
event_type_plot <- type_counts |>
  mutate(event_type = fct_reorder(event_type, n)) |>
  ggplot(aes(x = n, y = event_type)) +
  geom_col(fill = gold) +
  scale_x_continuous(labels = comma) +
  labs(
    title = "Thunderstorm wind and hail dominate event reports",
    subtitle = "NOAA Storm Events, 2024",
    x = "Number of event records",
    y = NULL
  )

event_type_plot
```

## What changed?

- **Data:** counts by event type
- **Geometry:** bars
- **Aesthetics:** count to x-position; event type to y-position
- **Scale:** comma-formatted counts
- **Coordinates:** Cartesian
- **Labels:** finding, scope, and units

## Checkpoint 2 · Change one mapping {.smaller}

::: {.checkpoint}
Change the plot to answer a question about `state` or `source`. Identify the data,
geometry, and aesthetic mapping you changed.
:::

```{r checkpoint2-starter}
#| eval: false
events |>
  count(___, sort = TRUE) |>       # choose state or source
  slice_head(n = 10) |>
  ggplot(aes(x = n, y = fct_reorder(___, n))) +
  geom_col(fill = gold) +
  labs(
    title = "___",
    x = "Number of event records",
    y = NULL
  )
```

## In the beginning...

Michael Florent van Langren published one of the first known statistical graphics in
1644. It compared estimates of the longitudinal distance between Toledo and Rome.

![](https://upload.wikimedia.org/wikipedia/commons/6/66/Grados_de_la_Longitud.jpg){fig-align="center" width=75%}

## [John Snow](https://www.theguardian.com/news/datablog/2013/mar/15/john-snow-cholera-map) Knows Something About Cholera

Snow mapped deaths around the Broad Street pump to connect a spatial pattern to a public
health hypothesis.

![](https://upload.wikimedia.org/wikipedia/commons/2/27/Snow-cholera-map-1.jpg){fig-align="center" width=62% fig-alt="John Snow's 1854 map of cholera deaths clustered around the Broad Street pump in Soho, London."}

## [Charles Minard's](https://www.datavis.ca/gallery/minard/minard.pdf) Map of Napoleon's Russian Disaster

The graphic combines location, direction, army size, time, and temperature in one
coherent account.

![](https://datavizblog.files.wordpress.com/2013/05/map-full-size1.png){fig-align="center" width=88%}

## [Florence Nightingale's](https://www.datavis.ca/gallery/flo.php) Rose Diagram

Nightingale used a statistical graphic to make preventable mortality visible to a
policy audience.

![](https://daily.jstor.org/wp-content/uploads/2020/08/florence_nightingagle_data_visualization_visionary_1050x700.jpg){fig-align="center" width=68%}

## [Milestones in Data Visualization History](https://friendly.github.io/HistDataVis/)

These graphics do more than decorate a result:

- they answer substantive questions,
- they make comparisons possible,
- they combine variables deliberately,
- they organize evidence into an argument.

## [Edward Tufte's](https://www.edwardtufte.com/tufte/) Principles of Data Visualization

- Focus attention on the substance, not the drawing technique.
- Make large or complex datasets more coherent.
- Encourage comparison.
- Describe, explore, and identify relationships.
- Avoid data distortion and unnecessary decoration.
- Use consistent graphic design.


## What about this spiral?

![A conventional time-series chart of new U.S. COVID-19 cases beside the New York Times spiral version of the same data.](../figures/nyt-covid-spiral-comparison.png){fig-align="center" width=86%}

Does the form make comparison easier, or does it only make the chart memorable?

## Infographics to communicate a story

An infographic can combine data, annotation, and structure for a broad audience. The
same standards still apply: clear comparisons, proportional encodings, and an honest
connection between evidence and claim.

## [Alberto Cairo](https://www.albertocairo.com/) and the art of insight

Useful graphics balance:

- truth,
- function,
- beauty,
- insight.

Visual polish matters only after the evidence and comparison are sound.

## Checkpoint 3 · Translate the graph {.smaller}

::: {.checkpoint}
Rewrite “Event type counts” as a title that states the main finding. Then add one
sentence explaining the denominator: these are NOAA event records, not unique storms.
:::

```{r checkpoint3-starter}
#| eval: false
event_type_plot +
  labs(
    title = "___",
    caption = "Each bar counts ___, not ___."
  )
```

## Recap and next steps

- Visualize before analyzing.
- Know what one row represents.
- Build graphics from data, geometries, mappings, scales, and labels.
- Make the comparison easier—not merely more decorative.

Next time: one-variable categorical distributions, proportions, and uncertainty.

::: {.callout}
**Before Sunday:** [Lab 0 · Getting R, RStudio, and Quarto
running](../resources/getting-started.html). HW1 opens Sunday, August 23.
:::
