Module 5: Data visualization I

PUBHLT 0411 · Python for Public Health Data Analysis

Soumik Purkayastha

Dept. of Biostatistics and Health Data Science, University of Pittsburgh

November 10, 2026

Housekeeping/setup

Every code cell in this deck loads its own data, so any slide runs on its own.

micropip is specific to Python running inside a browser. In JupyterLab, import seaborn as sns is sufficient — seaborn ships with the course environment.

Graphics in Python

Summarising data, numerically or graphically, is a central part of any analysis. Three layers produce figures in Python:

1. matplotlib — the original plotting library. Every figure in Python is ultimately a matplotlib figure.

2. pandas .plot() — a shortcut that calls matplotlib directly from a DataFrame.

3. seaborn — statistical figures built on matplotlib: it takes a DataFrame and column names, and handles grouping, colour, and legends.

This module begins with matplotlib, which every other layer depends on, and then turns to seaborn. Module 6 continues with seaborn’s statistical layers, facets, scales, and themes.

The asthma data

Source: CDC PLACES 2024, model-based estimates for adults, all 67 Pennsylvania counties.

Adult asthma prevalence runs from 9.7% to 11.6%. The entire state fits inside two percentage points.

The question this module opens

A variable that hardly varies looks like a dead end. What else moves with it?

matplotlib: the base layer

Every matplotlib figure is two objects

1. The figure is the canvas: its size, its resolution, and the file it saves to

2. The axes is one set of coordinates drawn on that canvas: the data, labels, and ticks

plt.subplots() returns both, and nearly every figure in practice begins with that call.

ax is not “axis”

An axes is an entire plotting area. An axis is one of its edges, reached as ax.xaxis or ax.yaxis. The naming is unfortunate and permanent.

Scatterplots

Examines the relationship between two numeric variables.

matplotlib receives columns, not column names. A bare name is an undefined variable:

Histograms

A graphical summary of the distribution of one numeric variable. bins sets the number of bins, or their exact edges.

Histograms + reference lines

A second layer drawn on the same axes. ax.axvline() adds a vertical line at a value.

Boxplots

A graphical summary of a distribution: the median, the interquartile range (the box), and the spread beyond it (the whiskers).

Pairs plots

pd.plotting.scatter_matrix() draws every pairwise scatter among several numeric columns, with a histogram of each column on the diagonal.

Most useful for a handful of numeric columns.

seaborn and the grammar of graphics

The grammar of graphics and seaborn

A statistical figure is assembled from independent components (Wilkinson, 2005):

1. Data — a table, one row per observation

2. Mappings — which column drives which visual property: position, colour, shape, size

3. A mark — the geometric object that represents each row: a point, a line, a bar

In seaborn, the function name is the mark (scatterplot, lineplot, countplot), data= names the table, and every mapping is a keyword that takes a column name.

sns.scatterplot(data=joined,                # data
                x="smoking_prev_pct",       # mapping: column -> horizontal position
                y="asthma_prev_pct",        # mapping: column -> vertical position
                hue="metro")                # mapping: column -> colour

Goal

Build the following figure with seaborn, one component at a time.

First: an ordered categorical column

pandas sorts text alphabetically. When categories have a natural order, pd.Categorical() fixes it, and every figure and table then follows that order.

Text ↔︎ Plot (1 of 5)

Start with an empty axes.

Every figure starts here. The axes is primed to receive data, and nothing is drawn yet.

Text ↔︎ Plot (2 of 5)

Start with an empty axes. Using joined, map smoking to the x-axis and asthma to the y-axis. Represent each county with a point.

scatterplot is the mark. ax=ax places it on the axes created above.

Text ↔︎ Plot (3 of 5)

… Represent each county with a point. Map metro status to the colour and the shape of each point.

hue= maps a column to colour; style= maps a column to marker shape. seaborn builds the legend.

Text ↔︎ Plot (4 of 5)

… Map metro status to the colour and shape of each point. Title the figure and label both axes with units.

ax.set() sets several properties of the axes in one call.

The minimum for any figure that leaves a notebook

An x-label with units, a y-label with units, and a title that states what is plotted.

Text ↔︎ Plot (5 of 5)

… Title the figure and label both axes with units. Replace the default colours and title the legend.

This is the goal figure.

seaborn calls

data is seaborn’s first argument and its name can be omitted. pandas .plot.scatter() draws the same mark from the DataFrame itself.

The mappings x= and y= must always be named.

Mapping versus setting

Mapping Setting
Drives the property from a column in the data a constant
Passed as a column name, to x, y, hue, style, size a value, to color, marker, s, alpha, linewidth, linestyle
Example hue="metro" color="#003594"
Legend built automatically none

Mappings are seaborn arguments. Settings are matplotlib arguments, which seaborn passes through to every mark.

Colour and shape

Both mapped to columns: colour to region, shape to metro status.

Size

Mapped to a column (left), and set to a constant (right).

Transparency

Set to a constant between 0 and 1. seaborn has no mapping for transparency.

Passing a column name to a setting is an error:

sns.scatterplot(data=asthma, x="smoking_prev_pct", y="asthma_prev_pct",  # data and positions
                alpha="metro")      # TypeError: alpha must be numeric or None, not a string

Linetype

sns.lineplot() maps style= to the dash pattern of each line.

Default aesthetics

Once a column is mapped, seaborn chooses the rest:

1. Axis labels — the column names: smoking_prev_pct

2. Legend title — the column name: metro

3. Colours — the deep palette, assigned in the order the groups first appear in the data

4. Markers and dashes — a fixed sequence: circle, cross, diamond, …

5. Category order — order of appearance, unless the column is a pd.Categorical

Each default has an override: ax.set(), .set_title() on the legend, palette=, markers=, order= or a categorical column.

Choosing a figure

The choice of figure follows from two questions: what type is each variable, and how many variables are shown.

Variables Figure seaborn matplotlib
One categorical Bar of counts countplot ax.bar
One numeric Histogram, boxplot histplot, boxplot ax.hist, ax.boxplot
Numeric by categorical Boxplot per group boxplot ax.boxplot
Two categorical Grouped bar of counts countplot(hue=) —
Two numeric Scatter scatterplot ax.scatter
Numeric over time Line lineplot ax.plot

A line asserts that consecutive points are connected. Categories are never joined by a line.

sns.countplot(): one and two variables

The height of each bar is the number of rows in each category.

A truncated axis manufactures a difference

Identical data. The right panel implies Philadelphia has three times the asthma burden of Clinton County. The true difference is 0.4 percentage points.

The rule for bars

A bar encodes value by length, so its baseline must be zero. Truncating the axis breaks the correspondence between length and value.

Describing what the figure shows

.describe() summarises every numeric column at once

Eight numbers per column: the count, the mean, the standard deviation, the minimum, the three quartiles, and the maximum.

count is the first number to read

It reports non-missing values. A count below the number of rows means missing data is present in that column.

.groupby() and .agg() describe each group

The comparison this table makes

Metro and nonmetro counties differ by 0.17 percentage points in asthma prevalence, and by 2.34 percentage points in smoking prevalence.

.corr() measures how two columns move together

A correlation runs from −1 to +1. It reports the strength and direction of a straight-line relationship, and nothing else.

The answer to the opening question: asthma moves with smoking, at r = +0.659 across 67 counties.

What a correlation cannot establish

It cannot establish cause. It cannot detect a curved relationship. It is distorted by outliers. And these are county averages, so it describes counties, not people.

Session outcomes

1. The figure/axes model, and plt.subplots() as the entry point to every figure

2. matplotlib marks: ax.scatter(), ax.hist(), ax.boxplot(), and layers such as ax.axvline()

3. Pairs plots with pd.plotting.scatter_matrix()

4. The grammar of graphics in seaborn: data, mappings, and the mark as the function name

5. Mapping versus setting: hue, style, size against color, marker, s, alpha

6. Ordered categories with pd.Categorical(); labels with ax.set(); colours with palette=

7. Choosing a figure from the variable types; countplot for counts; zero baselines for bars

8. .describe(), grouped .agg(), and .corr() as co-movement, never cause

Preparation for the lab, Thursday 11/12

The lab builds each figure type from this session on the course datasets, and repairs a figure that misleads without raising an error.

Module 6 adds seaborn’s statistical layers, facets, scales, and themes — and the question of when a figure of counts is really a figure of population.

That’s all folks!

See you on Thursday!