Module 6: Data visualization II

PUBHLT 0411 · Python for Public Health Data Analysis

Soumik Purkayastha

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

November 17, 2026

Housekeeping/setup

Every code cell in this deck loads its own data, so any slide runs on its own. In JupyterLab, import seaborn as sns is sufficient; the two micropip lines are for the browser only.

The maternal and infant data

Source: County Health Rankings & Roadmaps 2024. Low birthweight is the percentage of live births under 2,500 grams, 5.3% (Union) to 11.0% (Philadelphia).

Metro counties have the higher median low-birthweight rate, 8.1% against 7.3%, even though child poverty is higher in nonmetro counties.

The question this module opens

Does child poverty account for the metro difference, or does the difference persist at the same level of poverty?

More geoms

sns.histplot() and sns.kdeplot()

A histogram counts rows in bins. A density curve is a smoothed outline of the same distribution, scaled so its area is 1.

binwidth= and bins= are settings: fixed numbers, not columns, so they never go to a mapping.

sns.boxplot() and sns.violinplot()

A violin draws the density of each group on both sides of a centre line, where a boxplot draws only its quartiles.

hue= repeats the x column so each box takes its colour from palette; legend=False drops the legend, which would only repeat the axis labels.

seaborn’s three families

Every seaborn mark belongs to a family, and each family has a figure-level function that can split the data into panels.

Family Figure-level Axes-level marks
Relational: two numeric variables sns.relplot() scatterplot, lineplot
Distributional: one numeric variable sns.displot() histplot, kdeplot
Categorical: numeric by category sns.catplot() boxplot, violinplot, countplot, barplot

Axes-level functions draw on one ax=. Figure-level functions create their own figure and take col= and row= instead. The seaborn gallery shows a worked example of each.

Layers and statistical transformations

Layering: order matters

Each call draws on top of the previous one, so the layer that must be seen goes last.

zorder= overrides the order: a layer with a higher zorder is drawn in front.

Statistical transformations

Many marks compute something before drawing. countplot counts rows; barplot computes a mean of y and adds an error bar by default.

errorbar=None removes the error bar. The interval it draws is inference, which this course does not cover.

One summary, or one per group

A mapping applies to every layer that receives it. A layer without hue= summarises all rows at once.

Facets

Facets: one panel per group

col= gives each value of a column its own panel. col_wrap= wraps a long row of panels onto several lines.

relplot returns a FacetGrid, g, whose methods label every panel at once.

Facet grids: two conditioning variables

row= and col= together give one panel per combination. A numeric column becomes a condition once it is cut into groups.

Facets versus aesthetics

A facet removes the other groups from view. Drawing all rows in grey behind each panel restores the comparison.

g.axes.flat reaches each panel’s matplotlib axes, so any matplotlib call can add to it.

Rows or columns; shared axes

Panels stacked in a column share an x-axis, so their distributions line up. Panels side by side share a y-axis.

sharex=False or sharey=False gives each panel its own scale, at the cost of the comparison.

Position adjustments

Position adjustments: bars

When groups overlap in one bar, multiple= decides where each goes: stack, dodge (side by side), or fill (stack, scaled to proportions).

Position adjustments: histograms

Stacked histograms hide the shape of every group except the bottom one. Layering with transparency, or drawing outlines with element="step", keeps each group fully visible.

Scales

Scales: ticks, labels, and log axes

A scale maps data values to positions. matplotlib sets ticks automatically; set_xscale("log") spaces values by ratio, and a locator fixes the tick spacing.

Colour scales: named and manual palettes

palette= takes either a named palette, such as the ColorBrewer set "Dark2", or a dictionary from each group to a colour.

sns.color_palette("Dark2") displays a named palette’s colours.

Diverging colour scales: a correlation heatmap

A diverging palette has a neutral centre and two directions, which suits a value with a meaningful zero.

Themes

Built-in styles

A theme sets the non-data elements: background, grid, and ticks. seaborn has five styles.

sns.set_theme(style="white") sets the style for every later figure in the session.

Adjusting single elements

Individual elements change through matplotlib and two seaborn helpers: sns.despine() and sns.move_legend().

legend=False in the plotting call removes the legend entirely.

Combining and saving

Combining figures

plt.subplot_mosaic() lays out named panels from a sketch: each list is a row, and a repeated name spans several cells.

Saving figures

fig.savefig() writes the figure to a file. The extension chooses the format.

savefig() comes before plt.show(): after showing, the figure may be empty.

Appendix: why visualize?

Identical summaries, different data

Anscombe’s quartet (1973): four data sets with the same means, variances, and correlation.

A figure of counts often draws a map of population

The two lists share no counties. Deaths track population at r = +0.953; the rate does not.

Session outcomes

1. More marks: histplot, kdeplot, boxplot, violinplot, and seaborn’s three families

2. Layering in order, and zorder when the order must change

3. Statistical transformations: what countplot, barplot, and regplot compute

4. Facets with relplot and displot: col=, row=, col_wrap=, shared axes

5. Position adjustments: multiple="stack" / "dodge" / "fill" / "layer"

6. Scales: log axes, tick locators, named and manual palettes, diverging heatmaps

7. Themes: axes_style, despine, move_legend; combining with subplot_mosaic; savefig

8. Figures before summaries; rates before counts

Lab 6, now

Questions 1–3 in class (debug, facets and position, themes). All eight questions are due Thursday 11/19 at 11:59 pm.

That’s all folks!

On to Lab 6.