Skip to content

28. Visualization

Module 27 explored the course datasets with tables of numbers. A table answers “how much?”. A chart answers “what is the shape?”: a trend, a peak, a skew, a gap between groups, a point that does not belong. This module teaches the three plotting libraries that a Python data analyst uses every day. Matplotlib draws any chart you can describe. Seaborn builds statistical charts from a DataFrame in one call. Plotly Express makes interactive charts for the browser.

  • Choose a chart that answers a specific question, with a chart-choice guide.
  • Build Matplotlib charts with the object-oriented API: plt.subplots, subplot grids, titles, axis labels, legends and tick formatters.
  • Style charts with style sheets and rcParams, use color-blind-friendly palettes, annotate a peak or an outlier and save a figure with savefig.
  • Draw Seaborn distribution, categorical, relational, regression, heatmap, pair and facet plots from a pandas DataFrame.
  • Make interactive Plotly Express charts with hover details and save them as HTML.
  • Spot and fix charts that mislead: truncated bar axes, rainbow colors and overplotting.

Why visualize: same numbers, different stories

Section titled “Why visualize: same numbers, different stories”

Data visualization is the drawing of data as marks (points, lines, bars, colors) so that a person can see patterns. Your eyes compare positions and lengths much faster than they compare numbers in a table.

Summary statistics can hide the shape of the data. Anscombe’s quartet is a classic proof. It is four small datasets, published by the statistician Francis Anscombe in 1973. All four have almost the same means, variances and correlation:

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
print("matplotlib", mpl.__version__, "| seaborn", sns.__version__)
Output
matplotlib 3.11.2 | seaborn 0.13.2
x_123 = [10, 8, 13, 9, 11, 14, 6, 4, 12, 7, 5]
anscombe = {
"I": (x_123, [8.04, 6.95, 7.58, 8.81, 8.33, 9.96, 7.24, 4.26, 10.84, 4.82, 5.68]),
"II": (x_123, [9.14, 8.14, 8.74, 8.77, 9.26, 8.10, 6.13, 3.10, 9.13, 7.26, 4.74]),
"III": (x_123, [7.46, 6.77, 12.74, 7.11, 7.81, 8.84, 6.08, 5.39, 8.15, 6.42, 5.73]),
"IV": (
[8, 8, 8, 8, 8, 8, 8, 19, 8, 8, 8],
[6.58, 5.76, 7.71, 8.84, 8.47, 7.04, 5.25, 12.50, 5.56, 7.91, 6.89],
),
}
for name, (x, y) in anscombe.items():
x, y = np.array(x), np.array(y)
r = np.corrcoef(x, y)[0, 1]
print(f"{name:>3}: mean x {x.mean():.1f}, mean y {y.mean():.2f}, "
f"variance y {y.var(ddof=1):.2f}, r {r:.3f}")
Output
I: mean x 9.0, mean y 7.50, variance y 4.13, r 0.816
II: mean x 9.0, mean y 7.50, variance y 4.13, r 0.816
III: mean x 9.0, mean y 7.50, variance y 4.12, r 0.816
IV: mean x 9.0, mean y 7.50, variance y 4.12, r 0.817

The four tables look identical in summary. Now draw them. Do not worry about each plotting line yet; the next sections explain them all.

fig, axs = plt.subplots(2, 2, figsize=(8, 6), sharex=True, sharey=True,
layout="constrained")
for ax, (name, (x, y)) in zip(axs.flat, anscombe.items()):
slope, intercept = np.polyfit(x, y, deg=1)
ax.scatter(x, y)
ax.axline((0, intercept), slope=slope, color="gray", linestyle="--")
ax.set_title(f"Set {name}")
fig.suptitle("Same summary statistics, four different datasets")
plt.show()
Four scatter plots share the same dashed fitted line: set I is a noisy straight line, set II a smooth curve, set III a perfect line with one outlier, and set IV a vertical stack of points at x = 8 plus one far point at x = 19.
Anscombe's quartet: four datasets with the same means, variance and correlation.

Set I is a noisy straight line. Set II is a curve. Set III is a perfect line with one outlier. Set IV has no relationship at all: one far point creates the whole correlation. The same fitted line runs through all four. A chart shows at once what the statistics hide. This is why every EDA (module 27) draws the data before it trusts a summary.

Matplotlib is the base plotting library of Python. pandas and Seaborn draw with it. Every Matplotlib chart is a tree of objects:

  • The Figure is the whole image: the window on screen or the PNG file.
  • An Axes is one plot area inside the figure, with its own data, title and coordinate system. A figure can hold many Axes. (The word is always plural in form: one Axes, two Axes.)
  • Each Axes has two Axis objects, the x-axis and the y-axis. An Axis owns the ticks (the small marks with labels along it) and the axis label.
  • Everything you can see is an Artist: lines, bars, points, text, the legend. The Figure and the Axes are Artists too.
flowchart TD
    F["Figure<br/>the whole image"] --> A1["Axes<br/>plot area 1"]
    F --> A2["Axes<br/>plot area 2"]
    F --> S["suptitle,<br/>figure legend"]
    A1 --> X["XAxis and YAxis<br/>ticks, tick labels, axis labels"]
    A1 --> M["Lines, bars, points<br/>(artists with data)"]
    A1 --> T["title, legend,<br/>annotations"]

You change a chart by calling methods on these objects: ax.set_title(...), ax.xaxis.set_major_formatter(...), fig.savefig(...).

A backend is the part of Matplotlib that turns the tree into pixels. An interactive backend opens a window; the Agg backend draws into an image in memory, with no window. Servers, scheduled jobs and this course’s verifier use Agg. In a script, plt.show() opens a window and waits until you close it. In a Jupyter notebook, the chart appears under the cell.

Two interfaces: pyplot and object-oriented

Section titled “Two interfaces: pyplot and object-oriented”

Matplotlib offers two ways to give orders.

The pyplot interface (plt.plot, plt.title) keeps a hidden “current figure” and “current axes” and sends each command to them. It is short for a quick look in the REPL:

sensors = pd.read_csv("data/sensors.csv", parse_dates=["timestamp"])
s1_day = sensors.query("sensor_id == 'S1' and timestamp < '2024-05-02'")
plt.figure(figsize=(7, 3.5))
plt.plot(s1_day["timestamp"], s1_day["temperature_c"])
plt.title("Sensor S1, 1 May 2024")
print(type(plt.gcf()).__name__, type(plt.gca()).__name__, plt.gca().get_title())
plt.close()
Output
Figure Axes Sensor S1, 1 May 2024

plt.gcf() (“get current figure”) and plt.gca() (“get current axes”) return the hidden objects. plt.close() closes the figure without showing it.

The object-oriented interface (OO) gives you the objects and you call their methods. plt.subplots() returns a Figure and an Axes. This course uses the OO interface for every chart, because with several plot areas you always know which Axes a command changes:

import matplotlib.dates as mdates
fig, ax = plt.subplots(figsize=(7, 3.5))
ax.plot(s1_day["timestamp"], s1_day["temperature_c"], label="S1")
ax.set_title("Sensor S1, 1 May 2024")
ax.set_xlabel("Time of day")
ax.set_ylabel("Temperature (°C)")
ax.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M"))
ax.legend()
plt.show()
coolest = s1_day.loc[s1_day["temperature_c"].idxmin()]
warmest = s1_day.loc[s1_day["temperature_c"].idxmax()]
print(f"min {coolest['temperature_c']} °C at {coolest['timestamp']:%H:%M}, "
f"max {warmest['temperature_c']} °C at {warmest['timestamp']:%H:%M}")
Output
min 19.13 °C at 02:40, max 24.96 °C at 15:00
Sensor S1 on 1 May falls to its minimum of 19.13 °C at 02:40, rises to a peak of 24.96 °C at 15:00 and falls again by midnight.
One day of S1 readings with the object-oriented API.
pyplot (current axes) Object-oriented (explicit ax)
plt.plot(x, y) ax.plot(x, y)
plt.title("...") ax.set_title("...")
plt.xlabel("..."), plt.ylabel("...") ax.set_xlabel("..."), ax.set_ylabel("...")
plt.xlim(0, 10) ax.set_xlim(0, 10)
plt.legend() ax.legend()
plt.savefig("a.png") fig.savefig("a.png")
— ax.set(title="...", xlabel="...", ylabel="...") sets several at once

The setters on an Axes start with set_. A common bug is ax.title("..."): ax.title is a Text artist, not a method, so the call raises TypeError: 'Text' object is not callable.

A subplot is one Axes in a grid of Axes. plt.subplots(nrows, ncols) builds the grid in one call. It returns the Figure and the Axes:

  • one Axes for plt.subplots();
  • a 1-D NumPy array of Axes for one row or one column;
  • a 2-D array for a grid, indexed axs[row, col].
fig, axs = plt.subplots(2, 3, figsize=(9, 5))
print("2 x 3 grid:", type(axs).__name__, axs.shape)
fig, axs = plt.subplots(1, 3)
print("1 x 3 row:", axs.shape)
fig, ax = plt.subplots()
print("single:", type(ax).__name__)
fig, axd = plt.subplot_mosaic([["trend", "trend"], ["left", "right"]])
print("mosaic keys:", sorted(axd))
plt.close("all")
Output
2 x 3 grid: ndarray (2, 3)
1 x 3 row: (3,)
single: Axes
mosaic keys: ['left', 'right', 'trend']

The most useful options of plt.subplots:

Option Effect
figsize=(width, height) figure size in inches; the default is (6.4, 4.8)
sharex=True, sharey=True all Axes use the same x or y range, so you can compare panels by eye
layout="constrained" moves titles, labels and legends so that they do not overlap
axs.flat iterates over the Axes of a 2-D grid, row by row

plt.subplot_mosaic builds an uneven layout from a picture of names: [["trend", "trend"], ["left", "right"]] gives one wide panel on top and two below. It returns a dict from name to Axes.

A grid of small charts with the same axes, one per group, is called small multiples. Small multiples beat one crowded chart with eight colored lines: each panel is easy to read, and shared axes keep them comparable.

Style sheets, rcParams and color-blind-friendly palettes

Section titled “Style sheets, rcParams and color-blind-friendly palettes”

rcParams is Matplotlib’s dict of default settings: figure size, font size, colors, grid, spines (the four lines that frame the plot area). A style sheet is a named set of rcParams. plt.style.use(name) applies one for the rest of the program. plt.rcParams.update({...}) changes single settings.

About 1 in 12 men and 1 in 200 women have a color vision deficiency (color blindness): they cannot tell some colors apart, most often red and green. A color-blind-friendly palette picks colors that stay distinct for them. Matplotlib ships two such style sheets, petroff10 and tableau-colorblind10. Seaborn has the "colorblind" palette. The next Matplotlib charts use petroff10; the Seaborn section switches to Seaborn’s own theme:

plt.style.use("petroff10")
plt.rcParams.update({
"figure.figsize": (7, 4),
"axes.spines.top": False,
"axes.spines.right": False,
"axes.grid": True,
"grid.alpha": 0.3,
"axes.titleweight": "bold",
})
print("petroff10" in plt.style.available, "tableau-colorblind10" in plt.style.available)
print(plt.rcParams["axes.prop_cycle"].by_key()["color"][:4])
Output
True True
['#3f90da', '#ffa90e', '#bd1f01', '#94a4a2']

The color cycle (axes.prop_cycle) is the list of colors that Matplotlib gives to each new line or bar series in turn. You can name these colors "C0", "C1" and so on. For a temporary change, use a context manager (module 11): with plt.style.context("ggplot"): or with plt.rc_context({"font.size": 14}):. The settings return to normal when the block ends.

A colormap maps numbers to colors. Choose its kind by the data:

Kind For Good choices Avoid
qualitative palette categories with no order (regions, plans) colorblind, petroff10, tableau-colorblind10 more than about 8 colors
sequential colormap values from low to high (counts, rates) viridis, cividis, rocket, mako jet, rainbow: they invent edges and fail for color-blind readers
diverging colormap values around a meaningful center (correlation, change) vlag, RdBu, coolwarm, centered at 0 a sequential map for signed data

Color should never be the only way to tell series apart. Add direct labels, markers or line styles, so that the chart also works in grayscale print.

Each chart type is one Axes method:

Method Chart Use it for
ax.plot(x, y) line chart a value over an ordered x, usually time
ax.scatter(x, y) scatter plot the relationship between two numeric columns
ax.bar(labels, heights), ax.barh(...) bar chart a number per category
ax.hist(values, bins=...) histogram the distribution of one numeric column
ax.boxplot(groups, tick_labels=...) box plot distributions side by side
ax.fill_between(x, low, high) band a range or an uncertainty band around a line
ax.errorbar(x, y, yerr=...) error bars estimates with their uncertainty
ax.imshow(matrix) image or heatmap a 2-D grid of values

Module 27 used two of these charts; here is a short recap. A histogram splits the range of a numeric column into equal intervals called bins and draws one bar per bin, as tall as the number of values in it. A box plot draws the quartiles of a column (module 09) as a box from Q1 to Q3 with a line at the median. Its whiskers reach to the furthest points within 1.5 × IQR of the box, and points beyond them appear as dots. The IQR (interquartile range) is Q3 − Q1. Here are four of the types on the churn data:

customers = pd.read_csv("data/customers.csv")
churn_by_contract = customers.groupby("contract")["churned"].mean().sort_values()
plans = ["basic", "standard", "premium"]
charges_by_plan = [
customers.loc[customers["plan"] == p, "monthly_charges"] for p in plans
]
print(churn_by_contract.round(3))
Output
contract
two-year 0.032
one-year 0.088
month-to-month 0.296
Name: churned, dtype: float64
from matplotlib.ticker import PercentFormatter
fig, axs = plt.subplots(2, 2, figsize=(9, 6.5), layout="constrained")
bars = axs[0, 0].bar(churn_by_contract.index, churn_by_contract.to_numpy())
axs[0, 0].bar_label(bars, fmt="{:.1%}")
axs[0, 0].yaxis.set_major_formatter(PercentFormatter(xmax=1, decimals=0))
axs[0, 0].set(title="bar: churn rate by contract", ylabel="Churn rate")
axs[0, 1].hist(customers["tenure_months"], bins=24, edgecolor="white")
axs[0, 1].set(title="hist: tenure", xlabel="Tenure (months)", ylabel="Customers")
axs[1, 0].scatter(customers["tenure_months"], customers["total_charges"],
s=4, alpha=0.3)
axs[1, 0].set(title="scatter: tenure vs total charges", xlabel="Tenure (months)",
ylabel="Total charges (USD)")
axs[1, 1].boxplot(charges_by_plan, tick_labels=plans)
axs[1, 1].set(title="boxplot: monthly charges by plan", ylabel="USD per month")
plt.show()
Four panels: churn is 3.2% for two-year, 8.8% for one-year and 29.6% for month-to-month contracts; tenure is right-skewed with a spike at the 72-month cap; total charges fan out as tenure grows; monthly charges rise from basic to standard to premium, each with high outliers.
Four Matplotlib chart types on data/customers.csv.

ax.bar_label writes each bar’s value on it; fmt="{:.1%}" is a format spec from module 02. PercentFormatter(xmax=1) makes the axis match: it shows 0.30 as 30% (the next section explains formatters). alpha=0.3 makes points 70% transparent, so dense areas look darker. s=4 sets the point size.

A reader needs to know what each axis measures and in which unit. A chart without labels forces the reader to guess.

Element Method Tip
title ax.set_title("..."), fig.suptitle("...") state the finding: “Revenue peaks in December”
axis labels ax.set_xlabel, ax.set_ylabel include the unit: “Revenue (USD)”
legend ax.legend(title=..., loc=..., frameon=False) needs label= on each artist
tick positions and labels ax.set_xticks(positions, labels=...) for month names or categories
axis range ax.set_ylim(0, None) None keeps the automatic upper limit
tick format ax.yaxis.set_major_formatter(...) thousands, percent, currency, dates
rotated labels ax.tick_params(axis="x", labelrotation=45) for long category names

A tick formatter turns a tick’s numeric value into its label text. Matplotlib has ready-made formatters in matplotlib.ticker. A formatter is callable: give it a value and a tick position, and it returns the label, so you can test one without a chart:

from matplotlib.ticker import FuncFormatter, PercentFormatter, StrMethodFormatter
thousands = FuncFormatter(lambda value, pos: f"{value / 1000:,.0f}k")
comma = StrMethodFormatter("{x:,.0f}")
print(thousands(241098, 0), "|", comma(3596523.83, 0))
Output
241k | 3,596,524

FuncFormatter wraps your own function. PercentFormatter(xmax=1) treats 1.0 as 100%; it needs the axis it formats, so you see it at work in Example 4. StrMethodFormatter uses a str.format pattern whose field is always named x. For dates, matplotlib.dates has DateFormatter("%b %Y") and ConciseDateFormatter, which picks short labels by itself.

An annotation is text, an arrow or a reference line that points the reader to what matters: the peak, the outlier, the threshold, the start of a campaign.

Method Draws
ax.annotate("text", xy=(x, y), xytext=(tx, ty), arrowprops={"arrowstyle": "->"}) text with an arrow to the point xy
ax.text(x, y, "text") text at a data position
ax.axhline(y), ax.axvline(x) a horizontal or vertical reference line across the Axes
ax.axhspan(y0, y1), ax.axvspan(x0, x1) a shaded band, such as a holiday season
ax.axline((x0, y0), slope=m) an infinite straight line (you used it for Anscombe)

xy and xytext are in data coordinates by default, the same units as the plotted values. The worked examples annotate a revenue peak, a temperature spike and a wear threshold.

fig.savefig(path) writes the figure to a file. The extension picks the format:

Format Kind Use it for
.png raster image (a grid of pixels) slides, web pages, chat, email
.svg vector image (shapes, scales without blur) web pages, editing in a drawing program
.pdf vector reports and papers

Two arguments matter most. dpi (dots per inch) sets the resolution of a raster image: a 7 × 4 inch figure at dpi=200 is 1400 × 800 pixels. bbox_inches="tight" trims empty margins and keeps labels that stick out. Call savefig before plt.show(): after the window closes, the figure can be empty. Save into an output/ folder, never into your data/ folder. Each open figure uses memory, so a script that draws hundreds of charts calls plt.close(fig) after saving each one.

Seaborn: statistical charts from a DataFrame

Section titled “Seaborn: statistical charts from a DataFrame”

Seaborn is a library built on Matplotlib. You give it a DataFrame and column names; it groups, aggregates, picks colors, adds a legend and labels the axes for you. The import name is sns.

Seaborn works best with long-form data: one row per observation and one column per variable, as in data/sales.csv. (Module 16 called this shape tidy data. Module 25’s melt turns a wide table into long form.) You then map columns to visual properties. Seaborn calls this a semantic mapping:

Parameter Maps a column to Example
x, y position x="tenure_months"
hue color hue="contract"
size point size size="support_tickets"
style marker or line style style="channel"
col, row separate panels (figure-level functions only) col="category"

sns.set_theme() applies Seaborn’s look to all later charts, Matplotlib ones included. The rest of this page uses a white grid and the color-blind palette:

sns.set_theme(style="whitegrid", palette="colorblind")
fig, ax = plt.subplots(figsize=(7, 4))
sns.scatterplot(
data=customers, x="tenure_months", y="total_charges",
hue="plan", hue_order=plans, s=10, alpha=0.5, ax=ax,
)
ax.set(title="Total charges grow with tenure, faster on dearer plans",
xlabel="Tenure (months)", ylabel="Total charges (USD)")
plt.show()
Total charges rise with tenure in three fans of points; premium customers form the steepest fan and basic customers the flattest.
One call: Seaborn maps the plan column to color and builds the legend.

Seaborn functions come in two levels:

Kind Axes-level function Figure-level function Use
distribution histplot, kdeplot, ecdfplot displot the shape of one variable
categorical boxplot, violinplot, barplot, countplot, stripplot, pointplot catplot a number across categories
relational scatterplot, lineplot relplot two numeric variables, or a value over time
regression regplot lmplot a fitted line through a scatter
matrix heatmap clustermap a 2-D table of values
multi-variable — pairplot, jointplot many pairs at once

An axes-level function draws into one Axes. Pass ax= to place it in your own subplot grid, and it returns that Axes. A figure-level function creates its own figure, with one panel per value of col= or row=. It returns a FacetGrid (or a PairGrid / JointGrid), an object that holds the figure (g.figure) and the grid of Axes (g.axes). Do not pass ax= to a figure-level function; set its size with height= (inches per panel) and aspect= (width ÷ height).

Plotly is a library for interactive charts: charts in a web page where the reader can hover over a mark to see its values, zoom into a range and click legend entries to hide series. The box that appears on hover is a tooltip. Plotly Express (plotly.express, imported as px) is Plotly’s short API. Like Seaborn, it takes a DataFrame and column names.

import plotly
import plotly.express as px
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])
region_channel = sales.groupby(["region", "channel"], as_index=False)["revenue"].sum()
print("plotly", plotly.__version__)
print(region_channel.round(0))
Output
plotly 7.1.0
region channel revenue
0 East online 426331.0
1 East store 567353.0
2 North online 377690.0
3 North store 510540.0
4 South online 383604.0
5 South store 508162.0
6 West online 331841.0
7 West store 491003.0
fig = px.bar(
region_channel, x="region", y="revenue", color="channel", barmode="group",
title="Revenue by region and channel, 2023–2024",
labels={"revenue": "Revenue (USD)", "region": "Region", "channel": "Channel"},
template="plotly_white", color_discrete_sequence=px.colors.qualitative.Safe,
)
fig.update_traces(hovertemplate="%{x}: %{y:,.0f} USD")
fig.show()
Revenue by region and channel, interactive · Open the interactive chart in a new tab

Hover over a bar to see its exact value. labels= renames columns in axis titles and tooltips. template="plotly_white" gives a clean background. px.colors.qualitative.Safe is a color-blind-friendly palette. hovertemplate sets the tooltip text: %{y:,.0f} formats the y value with a thousands separator. fig.show() opens the chart in your browser; fig.write_html("output/chart.html") saves it as one HTML file that anyone can open.

Matplotlib Seaborn Plotly Express
Output static image (PNG, SVG, PDF) static image (via Matplotlib) interactive HTML (static PNG with the kaleido package)
Strength full control of every element statistical charts in one call hover, zoom, dashboards
Input arrays or columns a DataFrame and column names a DataFrame and column names
Best for reports, papers, custom layouts EDA, comparing groups sharing in a browser, exploring many points

A chart can be correct and still mislead. The most common trap is a truncated axis: a bar chart whose value axis does not start at zero. A bar’s length encodes its value, so a cut-off axis exaggerates small differences:

by_region = sales.groupby("region")["revenue"].sum().sort_values()
print((by_region / 1000).round(1))
print(f"East is {by_region.max() / by_region.min() - 1:.0%} above West")
baseline = 800_000
visual = (by_region.max() - baseline) / (by_region.min() - baseline)
print(f"From an 800k baseline, East's bar is {visual:.1f} times as tall as West's")
Output
region
West 822.8
North 888.2
South 891.8
East 993.7
Name: revenue, dtype: float64
East is 21% above West
From an 800k baseline, East's bar is 8.5 times as tall as West's
fig, axs = plt.subplots(1, 2, figsize=(9, 3.5), layout="constrained")
for ax, bottom, title in [(axs[0], 800_000, "Misleading: axis starts at 800k"),
(axs[1], 0, "Honest: axis starts at 0")]:
ax.bar(by_region.index, by_region.to_numpy(), color="C0")
ax.set_ylim(bottom, 1_020_000)
ax.yaxis.set_major_formatter(thousands)
ax.set_title(title)
plt.show()
Left: with the axis starting at 800k, East's bar is 8.5 times as tall as West's. Right: from zero, the four regional bars differ only modestly, from 823k to 994k.
The same four numbers. A truncated axis makes a 21% gap look like an 8.5-fold gap.

Rules for honest charts:

  • Bar and area charts start at zero. Line charts may zoom in, because they encode position, not length; say so in the axis.
  • Keep the same axis range across panels that the reader compares (sharey=True).
  • Avoid 3-D effects and pie charts with many slices: people judge angles and areas badly. A sorted bar chart is almost always clearer.
  • Avoid two y-axes with different scales on one chart (ax.twinx()). The crossing point of the two lines depends only on the scales you chose.
  • Overplotting is when so many points overlap that you cannot see how dense an area is. Fix it with transparency (alpha), smaller points, a sample, or a 2-D histogram: sns.histplot(x=..., y=...), or a hexbin (ax.hexbin), which counts points in hexagonal cells and colors each cell by its count.

Start from the question, not from the chart type. Name what you compare, then pick the chart that makes that comparison easy.

flowchart TD
    Q{"What is the question?"} -->|"how is one variable spread?"| D["Distribution"]
    Q -->|"how do groups differ?"| C["Comparison"]
    Q -->|"how do two variables relate?"| R["Relationship"]
    Q -->|"how does it change over time?"| T["Trend"]
    Q -->|"what are the parts of a whole?"| P["Composition"]
    D --> D1["histogram, KDE, ECDF<br/>box or violin per group"]
    C --> C1["sorted bar chart<br/>bar + error bars, heatmap"]
    R --> R1["scatter, regplot<br/>hexbin if many points"]
    T --> T1["line chart<br/>small multiples per group"]
    P --> P1["stacked bar<br/>100% stacked bar"]
Question Chart Why Code
How are house prices spread? Is there skew? histogram: linear x to see the skew, log x to see the bulk shows the shape, the peak and the long tail sns.histplot(x="price"), then log_scale=True
Which neighborhood has higher prices, and how much do they overlap? box plot or violin plot compares medians, spread and outliers side by side ax.boxplot(...), sns.violinplot(...)
What share of customers stay below a tenure? ECDF reads percentiles directly, no bin choice sns.ecdfplot(x="tenure_months", hue="churned")
Which contract churns most, and is the gap real? bar chart with 95% CI error bars length shows the rate, the error bar shows the uncertainty sns.barplot(errorbar=("ci", 95))
How does revenue change month by month? line chart position over time shows trend and season ax.plot(...), sns.lineplot(...)
Does the season differ by category? small multiples (facets) one clean panel per group, shared x-axis sns.relplot(kind="line", col="category")
Do bigger houses cost more? scatter plot with a regression line each point is a house; the line shows the trend sns.regplot(...), sns.lmplot(...)
Which numeric columns move together? correlation heatmap a whole correlation matrix at a glance sns.heatmap(df.corr(), annot=True)
What does a two-way table look like? annotated heatmap color shows the pattern, numbers give the detail sns.heatmap(pivot, annot=True)
What is the channel mix per year? 100% stacked bar compares shares when the totals differ ax.bar(..., bottom=...)
Which day had the spike, and what else happened then? interactive line chart hover shows the date and every value px.line(..., hover_data=[...])

Example 1 — Plot the monthly revenue trend

Section titled “Example 1 — Plot the monthly revenue trend”

Goal: The sales team asks for one chart of monthly revenue that compares 2023 with 2024 and points out the peak. Build it with Matplotlib from data/sales.csv and save it as a PNG for the monthly report.

monthly = sales.set_index("order_date")["revenue"].resample("ME").sum().to_frame()
monthly["year"] = monthly.index.year
monthly["month"] = monthly.index.month
print(monthly.head(3))
print("peak:", monthly["revenue"].idxmax().date(), round(monthly["revenue"].max()))
Output
revenue year month
order_date
2023-01-31 107329.60 2023 1
2023-02-28 77405.21 2023 2
2023-03-31 106542.74 2023 3
peak: 2024-12-31 302912

resample("ME") groups the daily rows into calendar months and labels each month by its last day. The year and month columns let you draw one line per year on a shared January–December axis.

fig, ax = plt.subplots()
for year, group in monthly.groupby("year"):
ax.plot(group["month"], group["revenue"], marker="o", label=str(year))
ax.legend()
plt.show()
Two lines of monthly revenue for 2023 and 2024 with months shown as numbers 2 to 12, no axis labels and a y-axis starting near 70,000; both lines rise sharply in months 11 and 12.
A first draft: correct, but hard to read.

The data is right, but the chart is not finished. The months show as numbers. The y-axis has no label or unit, and it starts near 70,000, which makes the February dip look deeper than it is. Nothing tells the reader what to look at.

Step 3 — Write a reusable plotting function

Section titled “Step 3 — Write a reusable plotting function”
import calendar
def plot_monthly(ax, monthly):
"""Draw one revenue line per year on ax and return ax."""
for year, group in monthly.groupby("year"):
ax.plot(group["month"], group["revenue"], marker="o", label=str(year))
ax.set_xticks(range(1, 13), labels=calendar.month_abbr[1:])
ax.yaxis.set_major_formatter(thousands)
ax.set_ylim(0, None)
ax.set(title="Revenue grows 19% in 2024 and peaks every December",
xlabel="Month", ylabel="Revenue (USD)")
ax.legend(title="Year", frameon=False)
return ax

A function that takes an Axes, draws on it and returns it works in any layout: a single chart, a grid or a dashboard. calendar.month_abbr is a sequence of month abbreviations with an empty string at index 0, so [1:] gives Jan to Dec. set_ylim(0, None) keeps zero visible, so the reader sees the real size of the change.

Step 4 — Annotate the peak and save the figure

Section titled “Step 4 — Annotate the peak and save the figure”
from pathlib import Path
fig, ax = plt.subplots()
plot_monthly(ax, monthly)
peak = monthly["revenue"].idxmax()
peak_value = monthly.loc[peak, "revenue"]
ax.annotate(f"Dec 2024: {peak_value / 1000:,.0f}k", xy=(12, peak_value),
xytext=(5.6, 285_000), arrowprops={"arrowstyle": "->", "color": "0.3"})
ax.axvspan(10.5, 12.5, color="gray", alpha=0.1)
ax.text(11.5, 20_000, "holiday\nseason", ha="center", fontsize=9)
Path("output").mkdir(exist_ok=True)
fig.savefig("output/monthly_revenue.png", dpi=200, bbox_inches="tight")
print(Path("output/monthly_revenue.png").exists())
plt.show()
Output
True
Monthly revenue for 2023 and 2024 from January to December on an axis from zero; both lines rise sharply in November and December inside a shaded holiday season, and an arrow marks the December 2024 peak of 303k.
The finished chart: month names, a formatted axis from zero, a shaded season and an annotated peak.

The annotation reads its value from the data, so next month’s report updates by itself. arrowprops sets the arrow; give it a color, because some themes draw arrows white by default. ha="center" centers the text on its x position. The file is saved before plt.show().

Common mistakes:

  • Plotting the 731 daily values instead of 24 monthly totals. Daily revenue is so noisy that the season disappears. Aggregate to the level of the question.
  • Typing the peak value into the annotation. Read it from the data with idxmax and .loc.
  • Calling plt.savefig after plt.show(). The saved file can be blank. Save first.

Example 2 — Build a sensor monitoring panel

Section titled “Example 2 — Build a sensor monitoring panel”

Goal: The facilities team monitors four sensors in data/sensors.csv. They want to see two known problems at a glance: sensor S3 drifts upward, and sensor S4 vibrates more and more from May 12. Build a grid of small multiples with thresholds and annotations.

Step 1 — Reshape the readings to one column per sensor

Section titled “Step 1 — Reshape the readings to one column per sensor”
temps = sensors.pivot(index="timestamp", columns="sensor_id", values="temperature_c")
daily_temps = temps.resample("D").mean()
print(temps.shape)
print(daily_temps.iloc[[0, -1]].round(2))
Output
(2016, 4)
sensor_id S1 S2 S3 S4
timestamp
2024-05-01 22.06 24.49 21.29 26.04
2024-05-14 22.02 24.32 25.85 25.94

pivot turns the long table into a wide one with one column per sensor, so each panel plots one column. The daily means confirm the drift: S3 rises by about 4.6 °C while the others stay flat.

Step 2 — Draw the temperature panels with shared axes

Section titled “Step 2 — Draw the temperature panels with shared axes”
fig, axs = plt.subplots(2, 2, figsize=(10, 6), sharex=True, sharey=True,
layout="constrained")
for ax, sensor in zip(axs.flat, temps.columns):
ax.plot(temps.index, temps[sensor], linewidth=0.5, alpha=0.6,
label="10-min reading")
ax.plot(daily_temps.index, daily_temps[sensor], linewidth=2, color="C1",
label="daily mean")
ax.axhline(33, color="C2", linestyle="--", linewidth=1)
ax.set_title(f"Sensor {sensor}")
arrow = {"arrowstyle": "->", "color": "0.3"}
axs[1, 0].annotate("drift: +4.6 °C in 14 days", xy=(daily_temps.index[-1], 25.9),
xytext=(daily_temps.index[1], 38), arrowprops=arrow)
spike_time, spike = temps["S2"].idxmax(), temps["S2"].max()
axs[0, 1].annotate(f"spike {spike:.1f} °C", xy=(spike_time, spike),
xytext=(spike_time + pd.Timedelta(days=2), 42), arrowprops=arrow)
axs[0, 0].text(temps.index[0], 33.5, "warn level 33 °C", fontsize=8)
axs[0, 0].legend(loc="upper right", fontsize=8)
for ax in axs[1]:
locator = ax.xaxis.get_major_locator()
ax.xaxis.set_major_formatter(mdates.ConciseDateFormatter(locator))
fig.suptitle("Temperature by sensor, 1–14 May 2024")
fig.supylabel("Temperature (°C)")
plt.show()
Four temperature panels with shared axes: the daily means of S1, S2 and S4 stay flat near 22, 24.6 and 26 °C, while S3's daily mean climbs from 21.3 to 25.9 °C; short spikes above the 33 °C warn line appear on every sensor, the highest at 44.9 °C on S2.
Small multiples with shared axes: the drift and the spikes stand out.

Shared axes make the panels comparable: you see at once that S4 runs warmest and S3 climbs. The raw line is thin and transparent so the daily mean stays readable on top. ConciseDateFormatter writes short date labels and puts the month once. fig.supylabel gives the whole grid one y label.

Step 3 — Show the vibration trend against the alert levels

Section titled “Step 3 — Show the vibration trend against the alert levels”
vib = sensors.pivot(index="timestamp", columns="sensor_id", values="vibration_mm_s")
rolling = vib["S4"].rolling(144, min_periods=72).median()
last_below = rolling[rolling <= 4.5].index[-1]
crossed = rolling.index[rolling.index > last_below][0]
fig, ax = plt.subplots(figsize=(8, 3.8))
ax.plot(vib.index, vib["S4"], linewidth=0.6, color="C0", label="S4 vibration")
ax.plot(rolling.index, rolling, color="C1", linewidth=2, label="rolling 1-day median")
ax.axhline(4.5, color="C2", linestyle="--", label="warn 4.5 mm/s")
ax.axhline(11.2, color="C3", linestyle="--", label="fail 11.2 mm/s")
ax.axvspan(pd.Timestamp("2024-05-12"), vib.index[-1], color="gray", alpha=0.12)
ax.text(pd.Timestamp("2024-05-12 06:00"), 15, "wear starts", fontsize=9)
ax.set(title=f"Sensor S4 stays above the warn level from {crossed:%d %B %H:%M}",
ylabel="Vibration (mm/s)")
ax.xaxis.set_major_formatter(mdates.ConciseDateFormatter(ax.xaxis.get_major_locator()))
ax.legend(loc="upper left", fontsize=8, ncols=2)
plt.show()
print("rolling median above 4.5 mm/s from", crossed)
Output
rolling median above 4.5 mm/s from 2024-05-12 17:50:00
S4 vibration stays near 3 mm/s until May 11; then its rolling median climbs past the 4.5 mm/s warn line in the evening of May 12, stays above it and reaches almost 9 mm/s on May 14, and a few readings exceed the 11.2 mm/s fail line.
S4 vibration with a rolling median and two alert levels.

A rolling median over 144 readings (one day of 10-minute readings) smooths the noise and ignores the spikes, which a rolling mean would not. Reference lines turn “the line goes up” into “the line crosses the warn level”. The title reads the crossing time from the data: the last time the median was at or below 4.5, plus one step. The shaded band marks the period of interest.

Step 4 — Confirm the picture with numbers

Section titled “Step 4 — Confirm the picture with numbers”
daily_vib = vib["S4"].resample("D").median()
print(daily_vib.loc["2024-05-10":].round(2))
Output
timestamp
2024-05-10 3.00
2024-05-11 3.23
2024-05-12 5.06
2024-05-13 6.71
2024-05-14 8.77
Freq: D, Name: S4, dtype: float64

The daily medians match the chart: about 3 mm/s until May 11, then 5.06, 6.71 and 8.77. A chart shows the pattern; a number makes it precise for the report.

Common mistakes:

  • One chart with four overlapping colored lines. The lines hide each other. Use small multiples.
  • Panels with different y ranges. A 2 °C change then looks as big as a 10 °C change. Use sharey=True when the reader compares panels.
  • A rolling mean to show a trend in spiky data. One spike pulls the mean up for a whole day. Use a rolling median.

Example 3 — Compare the distribution of house prices

Section titled “Example 3 — Compare the distribution of house prices”

Goal: A real-estate analyst wants to know how house prices in data/houses.csv are spread, and how three neighborhoods differ. Use Seaborn’s distribution plots.

houses = pd.read_csv("data/houses.csv")
print(houses["price"].describe().round(0).astype(int))
print("skew:", round(houses["price"].skew(), 2))
Output
count 3000
mean 476466
std 318751
min 117500
25% 278500
50% 376000
75% 560375
max 3730500
Name: price, dtype: int64
skew: 2.67

The mean (476,466) is far above the median (376,000), and the skew is strongly positive. A few expensive houses pull the mean up: the data has a long right tail.

Step 2 — Draw the histogram on a linear and a log scale

Section titled “Step 2 — Draw the histogram on a linear and a log scale”
def price_log_axis(ax):
"""Label a log-scale price axis in readable units."""
ticks = [1e5, 2e5, 5e5, 1e6, 2e6]
ax.set_xticks(ticks, labels=["100k", "200k", "500k", "1M", "2M"])
ax.minorticks_off()
fig, axs = plt.subplots(1, 2, figsize=(10, 3.8), layout="constrained")
sns.histplot(data=houses, x="price", bins=50, ax=axs[0])
axs[0].xaxis.set_major_formatter(FuncFormatter(lambda v, pos: f"{v / 1e6:.1f}M"))
axs[0].set(title="Linear scale: a long right tail", xlabel="Price (USD)")
sns.histplot(data=houses, x="price", bins=50, log_scale=True, ax=axs[1])
price_log_axis(axs[1])
axs[1].set(title="Log scale: close to a bell shape", xlabel="Price (USD, log scale)")
plt.show()
Left: house prices pile up between 200k and 500k with a long tail up to 3.7M. Right: on a log scale, the same prices form a nearly symmetric hump around the 376k median.
The same 3,000 prices on a linear and a logarithmic x-axis.

Module 27 drew this pair to measure the skew. On a log scale, equal distances mean equal ratios: the step from 100k to 1M is as wide as the step from 1M to 10M. log_scale=True also makes the bins equal in log units. Matplotlib labels a log axis with powers of ten such as 10⁵; price_log_axis replaces them with readable labels, and minorticks_off() removes the small unlabeled ticks. Money, populations and file sizes often look skewed on a linear scale and bell-shaped on a log scale. Module 35 uses this to model log price.

Step 3 — Compare neighborhoods with a KDE and an ECDF

Section titled “Step 3 — Compare neighborhoods with a KDE and an ECDF”
three = houses[houses["neighborhood"].isin(["Cedar Park", "Riverside", "Lakeview"])]
order = ["Cedar Park", "Riverside", "Lakeview"]
fig, axs = plt.subplots(1, 2, figsize=(10, 3.8), layout="constrained")
sns.kdeplot(data=three, x="price", hue="neighborhood", hue_order=order,
log_scale=True, common_norm=False, fill=True, alpha=0.3, ax=axs[0])
axs[0].set(title="KDE: the shape of each group", xlabel="Price (USD, log scale)")
sns.ecdfplot(data=three, x="price", hue="neighborhood", hue_order=order,
log_scale=True, ax=axs[1])
axs[1].axhline(0.5, color="gray", linestyle=":")
for ax in axs:
price_log_axis(ax)
axs[1].set(title="ECDF: read medians at 0.5", xlabel="Price (USD, log scale)")
plt.show()
print(three.groupby("neighborhood")["price"].median().loc[order])
Output
neighborhood
Cedar Park 249000.0
Riverside 476750.0
Lakeview 777000.0
Name: price, dtype: float64
Density curves and ECDFs for three neighborhoods: Cedar Park is narrow around 250k, Riverside centers near 480k and Lakeview is the widest around 780k; the ECDF curves cross the 0.5 line in that order.
Three neighborhoods as density curves and as cumulative curves.

A KDE (kernel density estimate) is a smooth version of a histogram: it puts a small bell curve on each value and adds them up. Its bandwidth sets how wide each bell is; bw_adjust=0.5 makes the curve more detailed, 2 smoother. common_norm=False scales each group to an area of 1, so a small group is not drawn flat. An ECDF (empirical cumulative distribution function) shows, for each price, the share of houses at or below it. Where a curve crosses 0.5 is the group’s median, so you read the medians from the chart: about 249k, 477k and 777k.

Common mistakes:

  • Comparing groups with overlapping histograms of counts. A group with more rows looks more important. Use stat="density", common_norm=False, a KDE or an ECDF.
  • Trusting a KDE near a hard limit. A KDE can draw density below 0 months or below the cheapest house. Check with a histogram.
  • Forgetting that the bin count changes the picture. Try two or three bins values before you conclude.

Goal: The retention team wants charts that show which customers in data/customers.csv churn, with honest uncertainty. Use Seaborn’s categorical plots and an annotated heatmap.

Step 1 — Compute churn rates by contract and plan

Section titled “Step 1 — Compute churn rates by contract and plan”
contracts = ["month-to-month", "one-year", "two-year"]
rates = customers.pivot_table(index="contract", columns="plan", values="churned",
aggfunc="mean").loc[contracts, plans]
print(rates.round(3))
Output
plan basic standard premium
contract
month-to-month 0.265 0.262 0.432
one-year 0.064 0.049 0.214
two-year 0.028 0.026 0.052

churned is 0 or 1, so its mean is the churn rate. Month-to-month customers churn most in every plan, and premium is the riskiest plan.

Step 2 — Draw the rates with 95% confidence intervals

Section titled “Step 2 — Draw the rates with 95% confidence intervals”
fig, ax = plt.subplots(figsize=(8, 4))
sns.barplot(data=customers, x="contract", y="churned", hue="plan", order=contracts,
hue_order=plans, errorbar=("ci", 95), seed=42, ax=ax)
ax.yaxis.set_major_formatter(PercentFormatter(xmax=1, decimals=0))
ax.set(title="Month-to-month premium customers churn most",
xlabel="Contract", ylabel="Churn rate")
ax.legend(title="Plan", frameon=False)
plt.show()
Churn rate by contract and plan: month-to-month churn is about 26% for basic and standard and 43% for premium; one-year premium is 21%; every two-year bar is below 6%; the error bars are widest for the smallest groups.
Churn rate by contract and plan; the black lines are 95% bootstrap confidence intervals.

barplot computes the mean of churned per bar. The error bar on each bar is its 95% confidence interval: the range where the true rate probably lies (module 09 introduced it, module 29 explains it). Seaborn computes it with a bootstrap; seed=42 makes it reproducible. Short error bars (month-to-month) mean many customers; long ones (two-year premium) mean few. Two bars whose intervals do not overlap differ for real. The reverse does not hold: overlapping intervals do not prove that there is no difference. Module 29 tests a difference properly.

Step 3 — Compare monthly charges with a split violin plot

Section titled “Step 3 — Compare monthly charges with a split violin plot”
fig, ax = plt.subplots(figsize=(8, 4))
sns.violinplot(data=customers, x="plan", y="monthly_charges", hue="churned",
order=plans, split=True, inner="quart", ax=ax)
ax.set(title="Churners pay slightly more within each plan", xlabel="Plan",
ylabel="Monthly charges (USD)")
ax.legend(title="Churned", frameon=False)
plt.show()
medians = customers.groupby(["plan", "churned"])["monthly_charges"].median().unstack()
print(medians.loc[plans].round(2))
Output
churned 0 1
plan
basic 37.78 38.68
standard 62.47 63.14
premium 96.83 98.12
Split violins of monthly charges for basic (about 38 USD), standard (about 63 USD) and premium (about 97 USD); in each plan, the churned half sits slightly higher than the retained half.
Monthly charges per plan, retained customers on the left half and churners on the right half.

A violin plot draws a KDE on both sides of a center line, so you see the full shape of each group. split=True puts the two hue groups on the two halves, which makes them easy to compare. inner="quart" draws the quartiles as dashed lines. Within each plan, the churners’ half sits a little higher.

Step 4 — Draw an annotated heatmap of contract and payment method

Section titled “Step 4 — Draw an annotated heatmap of contract and payment method”
by_payment = customers.pivot_table(index="contract", columns="payment_method",
values="churned", aggfunc="mean").loc[contracts]
fig, ax = plt.subplots(figsize=(8, 3.5))
sns.heatmap(by_payment, annot=True, fmt=".0%", cmap="rocket_r", vmin=0,
linewidths=1, ax=ax,
cbar_kws={"label": "churn rate", "format": PercentFormatter(1, decimals=0)})
ax.set(title="Electronic check + month-to-month: 37% churn", xlabel="Payment method",
ylabel="Contract")
ax.tick_params(axis="y", labelrotation=0)
plt.show()
print(by_payment.round(2))
Output
payment_method bank_transfer credit_card electronic_check paypal
contract
month-to-month 0.27 0.25 0.37 0.26
one-year 0.09 0.07 0.12 0.07
two-year 0.01 0.02 0.06 0.02
Heatmap of churn rate: the month-to-month row runs from 25% to 37%, darkest for electronic check; the one-year row runs from 7% to 12%; the two-year row from 1% to 6%.
Churn rate for each pair of contract and payment method.

A heatmap colors each cell of a table by its value. annot=True writes the value in each cell, and fmt=".0%" formats it. rocket_r is a sequential colormap reversed (_r), so higher churn is darker. vmin=0 anchors the color scale at zero. The darkest cell is the riskiest segment.

Common mistakes:

  • A bar chart of rates with no error bars. A 30% rate from 40 customers is far less certain than one from 2,000. Show the uncertainty.
  • palette="colorblind" without hue=. It prints a FutureWarning in Seaborn 0.13. Set the palette once with sns.set_theme, or pass hue= and legend=False.
  • A rainbow colormap such as jet on a heatmap. It invents sharp borders between cells. Use a sequential map for rates and a diverging map for signed values.

Example 5 — Explore relationships in house prices

Section titled “Example 5 — Explore relationships in house prices”

Goal: Before building a price model (module 35), the analyst checks how price relates to size and to the other numeric columns of data/houses.csv. Use regression plots, a correlation heatmap and a pair plot.

Step 1 — Fit one line per neighborhood with lmplot

Section titled “Step 1 — Fit one line per neighborhood with lmplot”
g = sns.lmplot(data=three, x="sqft", y="price", col="neighborhood", col_order=order,
hue="neighborhood", hue_order=order, height=3.2, aspect=1,
scatter_kws={"s": 8, "alpha": 0.4}, seed=42)
g.set_titles("{col_name}")
g.set_axis_labels("Size (sqft)", "Price (USD)")
for ax in g.axes.flat:
ax.yaxis.set_major_formatter(FuncFormatter(lambda v, pos: f"{v / 1e6:.1f}M"))
g.figure.suptitle("Each extra sqft adds far more in Lakeview", y=1.04)
plt.show()
for name, grp in three.groupby("neighborhood"):
slope = np.polyfit(grp["sqft"], grp["price"], deg=1)[0]
print(f"{name:<11} {slope:6.0f} USD per sqft")
Output
Cedar Park 77 USD per sqft
Lakeview 568 USD per sqft
Riverside 255 USD per sqft
Three scatter panels of price against size with fitted lines: the line is nearly flat in Cedar Park, moderate in Riverside and steep in Lakeview, where large houses reach 2M to 3.7M.
lmplot draws a scatter and a fitted regression line with a confidence band in each panel.

A regression line is the straight line that fits the points best (least squares, module 23). lmplot is the figure-level version of regplot: col= gives one panel per neighborhood. The shaded band is a 95% confidence interval for the line. The slopes from np.polyfit confirm what the panels show: size is worth several times more in Lakeview than in Cedar Park. A model must let the effect of size depend on the neighborhood.

corr = houses.select_dtypes("number").corr()
mask = np.triu(np.ones_like(corr, dtype=bool))
fig, ax = plt.subplots(figsize=(8, 6.5))
sns.heatmap(corr.iloc[1:, :-1], mask=mask[1:, :-1], annot=True, fmt=".2f",
cmap="vlag", vmin=-1, vmax=1, linewidths=0.5, annot_kws={"size": 8}, ax=ax)
ax.set_title("Correlation between the numeric columns of houses.csv")
plt.show()
top = corr["price"].drop("price").sort_values(key=abs, ascending=False)
print(top.head(4).round(2))
Output
sqft 0.73
bathrooms 0.63
bedrooms 0.63
school_rating 0.57
Name: price, dtype: float64
Lower-triangle correlation heatmap in red and blue: the bottom row shows that price correlates most with sqft (0.73), bedrooms and bathrooms (0.63) and school rating (0.57); sqft, bedrooms and bathrooms form a dark red block of strong correlations with each other.
Lower triangle of the Pearson correlation matrix, blue for negative and red for positive.

A correlation matrix holds the Pearson correlation (module 27) of every pair of columns. It is symmetric, so the mask hides the upper triangle and the diagonal of 1s. Masked cells would leave the first row and the last column empty, so corr.iloc[1:, :-1] drops them, and mask[1:, :-1] cuts the mask to the same shape. A diverging colormap with symmetric limits vmin=-1, vmax=1 puts its neutral middle color at 0 and makes the sign visible: red moves together, blue moves in opposite directions. Size has the strongest link to price. Distance has a negative link, but a correlation only measures straight-line relationships, so check the strongest pairs with a scatter plot.

cols = ["sqft", "distance_to_center_km", "school_rating", "price_k"]
sample = houses.sample(400, random_state=42).assign(price_k=lambda d: d["price"] / 1000)
g = sns.pairplot(sample, vars=cols, corner=True, height=1.9,
plot_kws={"s": 8, "alpha": 0.5}, diag_kws={"bins": 20})
g.figure.suptitle("Pairwise views of 400 houses", y=1.02)
plt.show()
print(sample[cols].isna().sum().to_dict())
Output
{'sqft': 0, 'distance_to_center_km': 0, 'school_rating': 10, 'price_k': 0}
Corner pair plot of size, distance, school rating and price for 400 houses: price rises with size and with school rating and is highest at middle distances; school rating takes whole values only.
A pair plot: histograms on the diagonal, scatter plots below it.

A pair plot (module 27 used one in its EDA) draws a scatter plot for every pair of columns and a histogram of each column on the diagonal. corner=True skips the mirrored upper half. A pair plot of all 11 columns would have 121 panels and take long to draw, so pick a few columns and a sample. price_k is the price in thousands of USD, which keeps the tick labels short. Seaborn drops missing values pair by pair, so the 400 rows still plot. The panels show that school_rating takes whole values from 1 to 10, and that distance relates to price in a curve, not a straight line.

Common mistakes:

  • Running sns.pairplot(houses) on every column and every row. It is slow and unreadable. Choose 3–5 columns and a sample of a few hundred rows.
  • Reading a correlation near 0 as “no relationship”. A U-shape has a correlation near 0. Look at the scatter plot.
  • A sequential colormap for correlations. Negative values then look “low” instead of “opposite”. Use a diverging map with symmetric limits, vmin=-1, vmax=1.

Example 6 — Compare seasons across product categories

Section titled “Example 6 — Compare seasons across product categories”

Goal: The merchandising team asks whether every category has the same seasonal pattern in data/sales.csv. Use figure-level Seaborn functions to draw one panel per category and per channel.

Step 1 — Build a long table of monthly revenue by category

Section titled “Step 1 — Build a long table of monthly revenue by category”
cat_month = (
sales.assign(year=sales["order_date"].dt.year.astype(str),
month=sales["order_date"].dt.month)
.groupby(["category", "year", "month"], as_index=False)["revenue"].sum()
)
print(cat_month.shape)
print(cat_month.head(3))
totals = cat_month.groupby("category")["revenue"].sum()
print(f"Electronics / Books revenue: {totals['Electronics'] / totals['Books']:.0f}x")
Output
(144, 4)
category year month revenue
0 Beauty 2023 1 4404.89
1 Beauty 2023 2 4251.36
2 Beauty 2023 3 3944.87
Electronics / Books revenue: 17x

Each row is one category in one month of one year: 6 × 2 × 12 = 144 rows. This long form is what figure-level functions expect. The year is text on purpose: Seaborn treats a numeric hue as a quantity and colors it with a light-to-dark scale, but a text hue gets distinct palette colors.

Step 2 — Draw small multiples with relplot

Section titled “Step 2 — Draw small multiples with relplot”
g = sns.relplot(data=cat_month, x="month", y="revenue", hue="year", col="category",
col_wrap=3, kind="line", marker="o", height=2.6, aspect=1.3,
facet_kws={"sharey": False})
g.set_titles("{col_name}")
g.set_axis_labels("Month", "Revenue (USD)")
for ax in g.axes.flat:
ax.set_xticks([1, 4, 7, 10], labels=["Jan", "Apr", "Jul", "Oct"])
ax.yaxis.set_major_formatter(FuncFormatter(lambda v, pos: f"{v / 1000:g}k"))
ax.set_ylim(0, None)
g.figure.suptitle("Sports peaks in early summer, the rest in November–December",
y=1.03)
plt.show()
peaks = cat_month.loc[cat_month.groupby(["category", "year"])["revenue"].idxmax()]
print(peaks.pivot(index="category", columns="year", values="month"))
Output
year 2023 2024
category
Beauty 12 12
Books 12 12
Clothing 11 12
Electronics 12 12
Home 12 11
Sports 5 6
Six panels of monthly revenue by category for 2023 and 2024: Beauty, Books, Clothing, Electronics and Home peak in November and December, Sports peaks in May and June, and 2024 lies above 2023 in most months.
Monthly revenue per category, one panel each, 2023 and 2024 as two lines.

col="category" with col_wrap=3 draws six panels in two rows. sharey=False gives each panel its own y range, because Electronics earns about 17 times more than Books (the ratio printed in Step 1) and would flatten every other panel. That is a deliberate trade: you compare shapes, not levels, and the panel titles and axes say so. The table of peak months confirms the summer peak of Sports.

Step 3 — Compare weekdays per channel with catplot

Section titled “Step 3 — Compare weekdays per channel with catplot”
daily = sales.groupby(["order_date", "channel"], as_index=False)["revenue"].sum()
daily["weekday"] = daily["order_date"].dt.day_name().str[:3]
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
g = sns.catplot(data=daily, x="weekday", y="revenue", col="channel", kind="bar",
order=days, color="C0", errorbar=("ci", 95), seed=42, height=3.2,
aspect=1.4)
g.set_titles("{col_name}")
g.set_axis_labels("", "Mean daily revenue (USD)")
plt.show()
weekday_means = daily.pivot_table(index="channel", columns="weekday", values="revenue")
print(weekday_means[days].round(0))
Output
weekday Mon Tue Wed Thu Fri Sat Sun
channel
online 1964.0 1489.0 1988.0 1722.0 2496.0 2626.0 2334.0
store 2290.0 2482.0 2313.0 2710.0 3102.0 3739.0 3302.0
Mean daily revenue by weekday for online and store sales: both peak on Saturday, at about 2,600 USD online and 3,700 USD in store; online revenue is lowest on Tuesday.
Mean daily revenue by weekday, store and online side by side.

catplot(kind="bar") is the figure-level barplot: same arguments, plus col=. color="C0" gives every bar one color, because the weekday is already on the x-axis and a color per day would add nothing. Both channels peak on Saturday. The error bars show that only the gap between the weekend and the early week clearly exceeds the noise, such as Tuesday against Saturday; the intervals of neighboring days overlap.

Step 4 — Build a FacetGrid by hand for a custom panel

Section titled “Step 4 — Build a FacetGrid by hand for a custom panel”
daily["year"] = daily["order_date"].dt.year.astype(str)
def mark_median(data, color=None, **kwargs):
"""Draw the median of one panel's revenue as a dashed vertical line."""
median = data["revenue"].median()
plt.axvline(median, color="C3", linestyle="--", linewidth=1.5)
plt.text(median, 0.95, f" median {median:,.0f}", color="C3", fontsize=8,
transform=plt.gca().get_xaxis_transform(), va="top")
g = sns.FacetGrid(daily, row="channel", col="year", height=2.3, aspect=1.7,
margin_titles=True)
g.map_dataframe(sns.histplot, x="revenue", bins=30)
g.map_dataframe(mark_median)
g.set_axis_labels("Daily revenue (USD)", "Days")
g.set_titles(row_template="{row_name}", col_template="{col_name}")
plt.show()
print(daily.groupby(["channel", "year"])["revenue"].median().unstack().round(0))
Output
year 2023 2024
channel
online 1285.0 1969.0
store 2445.0 2600.0
Four histograms of daily revenue, online and store by 2023 and 2024, each with a dashed median line: the online median rises from 1,285 to 1,969 USD and the store median from 2,445 to 2,600 USD.
A FacetGrid with one row per channel and one column per year; each panel marks its own median.

relplot, displot and catplot build a FacetGrid for you. Build it yourself when a panel needs something that no figure-level function draws. sns.FacetGrid(data, row=..., col=...) creates the empty grid. g.map_dataframe(func, ...) then calls func once per panel with that panel’s rows as data, with the panel’s Axes as the current Axes. So mark_median can use plt.axvline and draws each panel’s own median. margin_titles=True writes the row names on the right edge. The medians confirm what the panels show: online days grew more than store days from 2023 to 2024.

Common mistakes:

  • sharey=False without saying so. A reader compares heights across panels by habit. Use it only to compare shapes, and title the chart for shapes.
  • Passing ax= to relplot or catplot. Figure-level functions make their own figure and ignore or reject ax. Use the axes-level function (lineplot, barplot) inside your own grid.
  • Weekday names in alphabetical order (Fri, Mon, Sat…). Pass order= with the real order.

Example 7 — Explore web traffic interactively

Section titled “Example 7 — Explore web traffic interactively”

Goal: The marketing team wants to explore three years of data/web_traffic.csv in the browser: hover over any day, zoom into a campaign and compare spend with visits. Build two Plotly Express charts and save one as an HTML file to share.

Step 1 — Load the data and flag campaign days

Section titled “Step 1 — Load the data and flag campaign days”
traffic = pd.read_csv("data/web_traffic.csv", parse_dates=["date"])
traffic["campaign"] = np.where(traffic["marketing_spend"] > 2000, "campaign", "normal")
print(traffic["campaign"].value_counts())
print(traffic.loc[traffic["visits"].idxmax(), ["date", "visits", "marketing_spend"]])
Output
campaign
normal 1062
campaign 34
Name: count, dtype: int64
date 2024-04-08 00:00:00
visits 18385.0
marketing_spend 4697.75
Name: 828, dtype: object

A day with more than 2,000 USD of spend belongs to one of the seven campaigns. The busiest day is the first day of the April 2024 campaign.

Step 2 — Draw an interactive line chart with hover details

Section titled “Step 2 — Draw an interactive line chart with hover details”
fig = px.line(
traffic, x="date", y="visits", hover_data=["signups", "marketing_spend"],
title="Daily visits, 2022–2024 (hover for details, drag to zoom)",
labels={"visits": "Visits", "date": "Date", "marketing_spend": "Spend (USD)",
"signups": "Signups"},
template="plotly_white",
)
starts = traffic[(traffic["campaign"] == "campaign")
& (traffic["campaign"].shift() == "normal")]
fig.add_scatter(x=starts["date"], y=starts["visits"], mode="markers",
name="campaign start", marker={"size": 9, "color": "#D55E00"})
fig.update_layout(hovermode="x unified")
fig.show()
print(len(starts), "campaign starts:")
print(", ".join(starts["date"].dt.strftime("%Y-%m-%d")))
Output
7 campaign starts:
2022-03-14, 2022-09-06, 2023-02-20, 2023-06-12, 2023-10-02, 2024-04-08, 2024-09-16
Daily web visits with campaign starts, interactive · Open the interactive chart in a new tab

hover_data adds columns to the tooltip. fig.add_scatter adds a second series to a Plotly Express figure. hovermode="x unified" shows one tooltip for all series at the hovered date. The five tracking outages are gaps in the line, because their visits value is missing. Drag across a campaign to zoom in; double-click to zoom out.

Step 3 — Compare spend and visits with a scatter plot

Section titled “Step 3 — Compare spend and visits with a scatter plot”
fig = px.scatter(
traffic, x="marketing_spend", y="visits", color="campaign",
hover_data={"date": "|%Y-%m-%d", "signups": True},
title="More spend, more visits: campaign days form their own cloud",
labels={"marketing_spend": "Marketing spend (USD)", "visits": "Visits"},
template="plotly_white", color_discrete_sequence=px.colors.qualitative.Safe,
opacity=0.6,
)
fig.show()
print(traffic.groupby("campaign")[["marketing_spend", "visits"]].mean().round(0))
Output
marketing_spend visits
campaign
campaign 4066.0 8758.0
normal 512.0 4215.0
Marketing spend against visits, interactive · Open the interactive chart in a new tab

Each point is a day. Hover to see its date: the farthest points are campaign starts. "|%Y-%m-%d" formats a date in the tooltip. Campaign days have about eight times the spend but only about twice the visits: visits do not rise in proportion to spend. (Part of the normal-day visits would come without any spend, so this ratio is not the effect of one extra dollar.)

Step 4 — Save the chart as a standalone HTML file

Section titled “Step 4 — Save the chart as a standalone HTML file”
fig.write_html("output/spend_vs_visits.html", include_plotlyjs="cdn")
size_kb = Path("output/spend_vs_visits.html").stat().st_size / 1024
print(f"saved, {size_kb:.0f} KB")
Output
saved, 61 KB

write_html saves the chart, its data and its interactivity in one file that opens in any browser. include_plotlyjs="cdn" loads the Plotly JavaScript library from the web and keeps the file small. The default, True, embeds the library (about 4.8 MB) so the file also works offline.

Common mistakes:

  • Sending a Plotly chart of millions of points. The HTML file holds every point and the browser slows down. Aggregate first or use px.density_heatmap.
  • Expecting fig.show() to save a file. It only opens the chart. Use fig.write_html (or fig.write_image for a PNG, with the kaleido package).
  • A tooltip that shows raw column names and long floats. Use labels=, hover_data formats and hovertemplate.
Mistake Symptom Fix
ax.title("Revenue") TypeError: 'Text' object is not callable Use ax.set_title("Revenue")
Mixing plt.title and several Axes The title lands on the last Axes you created Use the OO API: axs[0].set_title(...)
axs.set_title on a grid AttributeError: 'numpy.ndarray' object has no attribute 'set_title' Index the grid (axs[0, 1]) or loop over axs.flat
plt.savefig after plt.show() An empty or blank PNG Call fig.savefig(...) before plt.show()
Labels cut off in the saved file Long tick labels or a legend outside the image bbox_inches="tight" and layout="constrained"
Overlapping titles and labels in a grid Text runs into the next panel plt.subplots(..., layout="constrained")
Bar chart axis not starting at 0 Small differences look huge ax.set_ylim(0, None)
Different y ranges in panels the reader compares A small change looks as big as a large one sharey=True
palette= without hue= in Seaborn 0.13 FutureWarning: Passing palette without assigning hue is deprecated hue=<the x column>, legend=False, or color=
ci=95 in Seaborn FutureWarning about the ci parameter errorbar=("ci", 95)
sns.heatmap(..., center=0) with Matplotlib 3.11 a hidden PendingDeprecationWarning about set_bad symmetric vmin=-v, vmax=v instead of center=
sns.boxplot with Matplotlib 3.11 MatplotlibDeprecationWarning about vert ax.boxplot(..., orientation="vertical") or sns.violinplot(inner="box")
ax= passed to relplot, lmplot, catplot The chart ignores your grid Use lineplot, regplot, barplot with ax=
Thousands of overlapping points A solid blob with no visible density alpha=0.2, s=5, a sample, or hexbin
jet or rainbow colormap False edges; unreadable for color-blind readers viridis (sequential), vlag (diverging)
Hundreds of figures in a loop Memory grows; Matplotlib warns about too many open figures plt.close(fig) after savefig
Weekday or month labels in alphabetical order Fri, Mon, Sat… order=[...] in Seaborn, or sort by a number
  • Monitoring and operations: server dashboards show request rates and error rates as line charts with alert thresholds, the same axhline idea as the sensor panel. Tools such as Grafana draw them live.
  • Automation: a nightly job queries a database, draws charts with the Agg backend, saves PNG files with savefig and attaches them to an email or a chat message. No window ever opens.
  • Web development: Plotly charts embed in web apps (Plotly’s Dash framework is built on them). write_html produces a page you can upload as it is.
  • Software engineering and science: benchmark plots in pull requests, test-coverage trends and figures in papers are Matplotlib PDFs and SVGs.
  • Start from the question. Distribution → histogram, KDE, ECDF, box or violin. Comparison → sorted bars with error bars. Relationship → scatter and regression line. Trend → line chart. Many groups → small multiples.
  • A Matplotlib Figure holds Axes; each Axes holds the artists. Use the OO API: fig, ax = plt.subplots(), then ax.plot, ax.set_title, ax.set(...).
  • plt.subplots(rows, cols, sharex=..., sharey=..., layout="constrained") builds grids; plt.subplot_mosaic builds uneven layouts.
  • Label every axis with its unit, format ticks with matplotlib.ticker and matplotlib.dates, start bars at zero and state the finding in the title.
  • Style with plt.style.use, rcParams or sns.set_theme. Use color-blind-friendly palettes (petroff10, colorblind, Safe), sequential maps for magnitudes and diverging maps for signed values.
  • Annotate what matters with annotate, axhline and axvspan. Save with fig.savefig("output/x.png", dpi=200, bbox_inches="tight") before plt.show().
  • Seaborn maps DataFrame columns to x, y, hue, col. Axes-level functions take ax=; figure-level functions (displot, catplot, relplot, lmplot, pairplot) make their own figure and facets.
  • In Seaborn 0.13, use errorbar= and pair palette= with hue=. Draw box plots with Matplotlib until Seaborn fixes the vert warning.
  • Plotly Express gives interactive charts with tooltips; fig.show() opens them and fig.write_html saves them.

Q1. What is the difference between a Figure and an Axes in Matplotlib?

Answer

The Figure is the whole image or window. An Axes is one plot area inside it, with its own data, title and x and y axes. One Figure can hold many Axes, for example a 2 × 2 grid from plt.subplots(2, 2).

Q2. fig, axs = plt.subplots(2, 3). What is axs.shape, and how do you set the title of the panel in the second row, third column?

Answer

axs is a NumPy array of shape (2, 3). The panel is axs[1, 2] (indexes start at 0), so write axs[1, 2].set_title("...").

Q3. Why does ax.title("Monthly revenue") fail, and what is the fix?

Answer

ax.title is an attribute that holds a Text artist, not a method. Calling it raises TypeError: 'Text' object is not callable. Use ax.set_title("Monthly revenue"). The pyplot function plt.title(...) exists, which causes the confusion.

Q4. You want to compare the distribution of monthly charges for churned and retained customers. There are 4,037 retained and 963 churned customers. Why is a plain histogram of counts with hue="churned" a poor choice, and what is better?

Answer

The retained group has four times more rows, so its bars are four times taller and the churned shape looks flat. Normalize each group: sns.histplot(..., hue="churned", stat="density", common_norm=False), or use a KDE with common_norm=False, an ECDF or a split violin plot.

Q5. A bar chart shows regional revenue with the y-axis from 800,000 to 1,000,000. What is wrong, and when is a y-axis that does not start at zero acceptable?

Answer

Bar length encodes the value, so a truncated axis exaggerates differences: a 21% gap looks several times larger. Bars must start at zero. A line chart may use a zoomed axis, because it encodes values by position, not length, and the reader looks at changes.

Q6. What is the difference between an axes-level and a figure-level Seaborn function? Give one pair.

Answer

An axes-level function (histplot, scatterplot, barplot, regplot) draws into one Axes, accepts ax= and returns the Axes. A figure-level function (displot, relplot, catplot, lmplot) creates its own figure, can split the data into panels with col= and row= and returns a FacetGrid. Pairs: histplot/displot, scatterplot/relplot, barplot/catplot, regplot/lmplot.

Q7. Which colormap kind fits a correlation heatmap, and which settings make it honest?

Answer

A diverging colormap such as vlag or RdBu, because correlations have a meaningful center at 0 and a sign. Set symmetric limits, vmin=-1, vmax=1, so that 0 gets the neutral color and the same color always means the same correlation.

Q8. In Seaborn 0.13, sns.barplot(data=customers, x="contract", y="churned", palette="colorblind") prints a warning. Why, and how do you get the same chart without it?

Answer

Seaborn 0.13 deprecates palette= without hue=. Assign the x column to hue and hide the redundant legend: sns.barplot(data=customers, x="contract", y="churned", hue="contract", palette="colorblind", legend=False). For one color for all bars, use color="C0" instead.

Q9. Your script saves 300 charts in a loop and gets slower and slower. What is the cause and the fix?

Answer

Each plt.subplots() creates a figure that stays in memory until you close it. Matplotlib keeps all 300 open. Call plt.close(fig) after fig.savefig(...) in each iteration.

Q10. When would you choose Plotly Express over Matplotlib or Seaborn?

Answer

When the reader views the chart in a browser and benefits from interaction: hovering to see exact values or dates, zooming into a period, hiding series. Examples are a traffic dashboard or an exploration of thousands of points. For a printed report, a paper or a fixed PNG in a slide, Matplotlib or Seaborn is simpler.

Q11. What does bbox_inches="tight" do in fig.savefig, and what does dpi=200 change?

Answer

bbox_inches="tight" crops the saved image to the drawn content, so empty margins go and labels that stick out stay in. dpi=200 sets 200 pixels per inch for raster formats, so a 7 × 4 inch figure becomes 1400 × 800 pixels. It does not affect vector formats such as SVG and PDF.

Your progress

0 / 4 done

  • Exercises: 28 exercises from a first plt.subplots chart to a dashboard, an anomaly chart and an interactive explorer.
  • Mini-project: build a chart pack for the yearly sales review.
  • Cheat sheet: Matplotlib, Seaborn and Plotly Express calls, formatters, palettes and the chart-choice guide on one page.
  • Next module: 29. Statistics and probability puts numbers on the uncertainty you drew as error bars: distributions, confidence intervals and hypothesis tests.