Sub topic 8
Plots that can be read without you
This chapter assumes you can build a basic pandas and matplotlib plot, and that you know what a histogram and a box plot show. It covers how to choose a plot for a question and how to label it. A reader who opens the notebook next month, without you there, should be able to read each plot on its own.
What "readable without you" means
A plot is readable without you when a reader can answer four questions from the figure alone:
- What is being measured, and in what units?
- How many observations are shown?
- What does each axis, color, or line represent?
- What is the plot meant to show?
Default pandas plots answer almost none of these. An unlabeled histogram shows a shape, but the reader cannot tell whether the x-axis is dollars, cents, or days. Your own memory fills those gaps while you work, and a later reader has no such memory.
The rule is to treat every plot as a small document. It gets a title that states the subject, axis labels with units, and enough context (such as n) to judge how much to trust it. A markdown cell below it states the conclusion, as described in the findings-log chapter.
Choose the plot from the question
Start from the question and the variable types. Do not start from a favorite chart.
| Question | Variable types | Plot | Check before you trust it |
|---|---|---|---|
| What is the shape of this variable? | One numeric | Histogram | Try two bin counts |
| How are categories distributed? | One categorical | Bar chart of counts | Sort the bars, start the axis at zero |
| Does a numeric value differ by group? | Numeric by categorical | Box plot | Check the group sizes |
| Do two numbers move together? | Numeric and numeric | Scatter plot | Look for overplotting |
| Does something change over time? | Numeric by date | Line plot | Sort by date, check for gaps |
The next two chapters use these plots on real variables. Here the focus is on making each one honest and legible.
A labeled histogram helper
You will make many histograms in one notebook. If you label each one by hand, you will forget something on some of them. A small helper function makes the labeling consistent. The example below builds its own data, so it runs as shown.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
rng = np.random.default_rng(42)
df = pd.DataFrame({
"amount": rng.lognormal(mean=3.5, sigma=0.8, size=1000),
"region": rng.choice(["north", "south", "east", "west"], size=1000),
})
def hist_plot(series, title, xlabel, ylabel="Number of orders",
bins=30, log_x=False, ax=None):
"""Histogram with title, n, axis labels, and a median line."""
if ax is None:
_, ax = plt.subplots(figsize=(6, 4))
values = series.dropna()
if log_x:
bins = np.geomspace(values.min(), values.max(), bins + 1)
ax.set_xscale("log")
ax.hist(values, bins=bins, color="steelblue", edgecolor="white")
median = values.median()
ax.axvline(median, color="black", linestyle="--",
label=f"median = {median:,.1f}")
ax.set_title(f"{title} (n={len(values):,})")
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
ax.legend()
return ax
hist_plot(df["amount"], "Order amount distribution", "Amount (USD)")
plt.tight_layout()
plt.show()The helper puts the count of non-missing values in the title. It draws the median because the chapter's running example is right-skewed, where the mean misleads. It returns the axes, so you can draw it inside a larger figure by passing ax=.
Bins and scales change the story
A histogram is a summary, and the bin count is a choice that changes how it looks. Too few bins hide structure. Too many bins turn noise into false peaks. When you see a feature, such as a second hump, redraw with a different bins value before you believe it.
For right-skewed data, a log x-axis often shows the shape better than a linear one. The helper's log_x=True option uses bin edges that are evenly spaced on a log scale. Using linear bin edges on a log axis gives lopsided bars. The log option needs strictly positive values, so it fails on zeros. Mention the scale in the axis label or the title so nobody reads it as linear.
fig, axes = plt.subplots(1, 2, figsize=(11, 4))
hist_plot(df["amount"], "Linear scale", "Amount (USD)", ax=axes[0])
hist_plot(df["amount"], "Log scale", "Amount (USD, log axis)",
log_x=True, ax=axes[1])
plt.tight_layout()
plt.show()Bar charts and box plots
For a categorical variable, plot counts as bars. Sort them by size unless the categories have a natural order, such as months. Keep the value axis starting at zero. A bar's length encodes its value, so a truncated axis makes small differences look large.
fig, ax = plt.subplots(figsize=(6, 4))
counts = df["region"].value_counts()
counts.plot.bar(ax=ax, color="steelblue")
ax.set_title(f"Orders per region (n={counts.sum():,})")
ax.set_xlabel("Region")
ax.set_ylabel("Number of orders")
ax.tick_params(axis="x", rotation=0)
plt.tight_layout()
plt.show()The grouped box plot from the spine has one trap. When you call df.boxplot(column=..., by=...), pandas adds its own figure title, "Boxplot grouped by region". It also sets the subplot title to the column name. That is why the spine's example calls fig.suptitle("") and then sets its own axes title. If you skip that step, you get two competing titles.
Labeling checklist
Run through this list for every figure you plan to keep:
- The title names the variable and the population, for example "Order amount distribution (n=1,000)".
- Each axis has a label with units. Mention a log scale if you used one.
- Counts and proportions are not mixed up. Say which one the y-axis shows.
- Colors carry meaning only if a legend explains them. Do not rely on color alone, because some readers cannot tell certain colors apart.
- Reference lines, such as the median, are named in a legend.
- The figure size is large enough for tick labels not to overlap.
Plots for the notebook and plots for sharing
A plot that is clear inside the notebook can still lose its context when you copy it into a report. If a plot supports a conclusion you will share, save it with the same labels and a stable filename.
from pathlib import Path
FIG_DIR = Path("reports/figures")
FIG_DIR.mkdir(parents=True, exist_ok=True)
ax = hist_plot(df["amount"], "Order amount distribution", "Amount (USD)")
ax.figure.tight_layout()
ax.figure.savefig(FIG_DIR / "amount_hist.png", dpi=150)Saving from code, and not by right-clicking the output, means the file is regenerated whenever you run the notebook. It never goes stale.
Common mistakes
- Plotting before cleaning. An impossible value, such as a negative amount, stretches the axis and flattens everything else. Draw the plot after the cleaning step, and say so in the title or the markdown note.
- Overplotting. A scatter plot of tens of thousands of points becomes a solid blob. Lower the marker opacity with
alpha=0.2, use a smaller marker size, or plot a random sample. - Reading a pattern off one plot. A hump or an outlier is a hypothesis. Check it with a second view before you record it as a finding.
- Leaving the plot object in the output. The last line of a cell can print something like
<Axes: ...>. End plotting cells withplt.show()to keep the output clean.
Exercise
A teammate's notebook has a bar chart of average order amount per region. The y-axis starts at 90 and the bars range from 92 to 98. What two problems should you fix, and what would you add so the reader can judge the result?
Show answer
First, the truncated y-axis makes a small difference (about 6 units) look large, so start the axis at zero, since bar length encodes value. Second, the chart has no labels and no sample size: add a title that names the metric and population, axis labels with units, and the number of orders per region (in the title or the tick labels). Group sizes matter because an average over 5 orders is much less reliable than one over 5,000.
Exercise
You draw a histogram of amount and see a second small hump near the high end. What should you do before writing it up as a finding?
Show answer
Redraw the histogram with a different number of bins, and try a log x-axis, to see whether the hump persists. Then check it with another view, such as a box plot by region, or a count of how many orders fall in that range. Only record it as a finding, with the evidence next to it, if it survives these checks. Otherwise note it as a hypothesis.