Back to Tutorials
Python for AI
Beginner

Data Visualization: Plot It Before You Trust It

Four datasets with identical statistics and nothing else in common, a geyser whose histogram changes with every bin width, and a bar chart that turns 7% into sixfold. Drag, slide and see.

9 minInteractive: drag, click and try things as you read


A mean, a correlation or a best-fit line squeezes a whole dataset into one number, and a lot can hide in the squeeze: a curve, an outlier, two groups pretending to be one. A chart shows you all of it at once, which is why people who work with data plot it before they model it. Look at your data before you trust any number about it. Here you’ll meet four datasets that share their statistics but nothing else, then see how a chart’s own settings can hide a pattern or invent one.

Same numbers, different data#

In 1973 the statistician Francis Anscombe published four tiny datasets, eleven points each, to make a point to colleagues who trusted calculations over pictures. Each has the same mean (average) of x and of y, the same variance (how spread out the values are), the same correlation (how closely x and y move together, from −1 to 1) and the same best-fit line, the straight line that sits closest to the points.

Predict first

Four datasets share their means, variances, correlation and best-fit line, to two decimal places. How alike do they look when you plot them?

Try it
Anscombe’s quartet, the real 1973 values. The table is computed live from the points, so drag any point and its numbers change. In dataset III, drag the high point down onto the line the other ten points follow.

Only dataset I is what the numbers suggest: a cloud of points around a rising line. Dataset II is a curve, so a straight line is the wrong model for it however good its correlation looks. In dataset III, ten points sit on an almost perfect line and one stray value drags the line and the correlation away from them: move that point onto the line and the correlation jumps from 0.816 to almost exactly 1. Dataset IV has no relationship at all for ten of its points, which all share x = 8; one far-off point creates the entire correlation.

Every one of these problems would mislead a model trained on the data, and every one is obvious in a plot that takes one line of code.

Pick the chart for the question#

  • How is one thing spread out? A histogram: split the range into bins and draw a bar for how many values fall in each.
  • Do two things move together? A scatter plot, one dot per row, as in Anscombe’s quartet.
  • How does something change over time? A line chart.
  • How do a few groups compare? A bar chart.

Whichever you choose, label both axes and give the chart a title that says what it shows. The two sections below are about the settings that quietly change what a chart says.

Histograms: the bin width decides what you see#

Old Faithful, the geyser in Yellowstone, is famous for erupting on a fairly regular schedule. This dataset records the minutes between 272 of its eruptions. A histogram of those waits should show you whether the schedule really is regular, but the answer depends on a setting most people never touch: how wide each bin is.

Try it
Real data: minutes between eruptions of Old Faithful, 272 observations, as shipped with the R language. The histogram is recomputed live for each bin width; the yellow bars are its bumps, the bins taller than both neighbours.

The waits come in two groups, a short wait of about 50 to 55 minutes and a long one of about 80. With bins 4 to 15 minutes wide you see both. Make the bins 20 or 30 minutes wide and the two groups merge into one hump: a geyser that looks reliably average. Make them 1 to 3 minutes wide and the chart breaks into spiky noise, because each bin holds only a handful of eruptions. Matplotlib’s default of 10 bins happens to show both groups for this data. On other data it won’t, so try a few widths, and turn on “Show every eruption” to see the raw values the bars summarise.

Axes that tell the truth#

A bar chart says “this bar is twice as long, so this value is twice as big”. That only holds if the bars start at zero. Here are six months of takings at a made-up café: the best month is about 7% better than the first.

Predict first

June’s takings are 7% higher than January’s. If the bar chart’s y-axis starts at £18,000 instead of £0, how much taller does June’s bar look?

Try it
The takings are made up. The bars and the lie factor are computed live from the axis you choose.

Edward Tufte, who wrote some of the best-known books on data graphics, called this the lie factor: the size of the change a chart shows divided by the size of the change in the data. From zero it’s 1, an honest chart. From £18,000 it’s 76. Lines are different: they show change by position, not length, so a line chart can start its axis above zero to show detail, as long as the axis is clearly labelled. If you want to emphasise a small change, a line chart, or a chart of the change itself, is the honest way to do it.

In code#

Anscombe’s quartet in matplotlib and NumPy, free and local (pip install matplotlib numpy). It prints the statistics, then draws the four plots and saves them to a file:

import matplotlib.pyplot as plt
import numpy as np

# Anscombe's quartet, as published in 1973
x = [10, 8, 13, 9, 11, 14, 6, 4, 12, 7, 5]
quartet = {
    "I": (x, [8.04, 6.95, 7.58, 8.81, 8.33, 9.96, 7.24, 4.26, 10.84, 4.82, 5.68]),
    "II": (x, [9.14, 8.14, 8.74, 8.77, 9.26, 8.10, 6.13, 3.10, 9.13, 7.26, 4.74]),
    "III": (x, [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]),
}

fig, axes = plt.subplots(2, 2, figsize=(8, 6), sharex=True, sharey=True)
for ax, (name, (xs, ys)) in zip(axes.flat, quartet.items()):
    xs, ys = np.array(xs), np.array(ys)
    slope, intercept = np.polyfit(xs, ys, 1)
    r = np.corrcoef(xs, ys)[0, 1]
    print(f"{name:>3}: mean y {ys.mean():.2f}, variance y {ys.var(ddof=1):.2f}, r {r:.3f}, y = {intercept:.2f} + {slope:.3f}x")
    ax.scatter(xs, ys)
    ax.plot([2, 20], [intercept + slope * 2, intercept + slope * 20], color="grey")
    ax.set_title(f"Dataset {name}")
    ax.set_xlabel("x")
    ax.set_ylabel("y")
fig.tight_layout()
fig.savefig("anscombe.png", dpi=150)
#   I: mean y 7.50, variance y 4.13, r 0.816, y = 3.00 + 0.500x
#  II: mean y 7.50, variance y 4.13, r 0.816, y = 3.00 + 0.500x
# III: mean y 7.50, variance y 4.12, r 0.816, y = 3.00 + 0.500x
#  IV: mean y 7.50, variance y 4.12, r 0.817, y = 3.00 + 0.500x

The printed numbers agree; open anscombe.png and the four plots don’t. For a histogram, ax.hist(values, bins=20) sets the number of bins; try several.

What to remember

  • Summary statistics can match exactly while the data differs completely: plot it before you model it.
  • A histogram’s bin width can hide real structure (too wide) or invent it (too narrow), so try a few widths.
  • Bars must start at zero, because their length is the message; a line can zoom in if its axis is labelled.

Keep going

Sign in to save your place and keep a learning streak. Free, with Google.