Visualising Data
Summary statistics compress a column into a few numbers, and in doing so they hide things: two bumps, a gap, a wall of identical values, a cluster of mislabelled points. A picture shows them at once. Four kinds of plot cover most of data quality work: histograms for one numeric column, box plots for comparing groups, scatter plots for pairs of columns, and image grids for looking at the samples themselves. The Matplotlib course teaches the library; this lesson is about what to look for.
Histograms: the shape of one column
A histogram counts values in bins. It shows the centre and spread, but above all the shape: skew, several peaks, gaps, spikes at placeholder values, a wall at a sensor's maximum. Here is a weight column with three problems built in:
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(0)
kg = rng.normal(70, 11, 900)
lb = rng.normal(70, 11, 100) * 2.20462 # 10% recorded in pounds
weight = np.concatenate([kg, lb, np.full(40, 999.0)])
shown = weight[weight < 500] # the 999 placeholders would squash the plot
fig, axes = plt.subplots(1, 2, figsize=(9, 3))
axes[0].hist(shown, bins=40)
axes[0].set_title("weight: 40 bins")
axes[0].set_xlabel("recorded value")
axes[1].hist(shown, bins=5)
axes[1].set_title("same data: 5 bins")
fig.tight_layout()
plt.show()
print(f"values: {len(weight)}, placeholders 999: {int((weight == 999).sum())}, "
f"median {np.median(weight):.1f}, mean {weight.mean():.1f}")values: 1040, placeholders 999: 40, median 71.7, mean 113.0
With 40 bins, the second bump around 150 (the pounds) is obvious; with 5 bins it blurs into a long right tail. Always try a few bin counts. The 999 placeholders were removed before plotting, because a single far-away spike stretches the axis until everything else is one bar: plot the bulk of the data and report the extremes separately. The summary line shows how much the placeholders and the pounds pull the mean (113.0) above the median (71.7).
Box plots: comparing groups
A box plot draws the quartiles as a box, the median as a line, whiskers to the most extreme points within 1.5 IQR of the box, and every point beyond them individually: exactly Tukey's rule from Outlier Detection. Several boxes side by side compare a feature across classes, sources or time periods:
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.datasets import load_wine
wine = load_wine(as_frame=True)
df = wine.frame
fig, axes = plt.subplots(1, 3, figsize=(10, 3))
for ax, col in zip(axes, ["proline", "flavanoids", "color_intensity"]):
groups = [df.loc[df["target"] == k, col] for k in range(3)]
ax.boxplot(groups)
ax.set_xticks([1, 2, 3], wine.target_names)
ax.set_title(col)
fig.tight_layout()
plt.show()
for col in ["proline", "flavanoids", "color_intensity"]:
print(f"{col:16} medians by class:", df.groupby("target")[col].median().round(2).tolist())proline medians by class: [1095.0, 495.0, 627.5]
flavanoids medians by class: [2.98, 2.03, 0.68]
color_intensity medians by class: [5.4, 2.9, 7.55]
Where the boxes of different classes barely overlap, that feature separates them well on its own: proline sets class 0 apart, flavanoids class 2, and color_intensity class 1. Box plots by source (clinic, device, month) are just as useful: a box that sits apart from the others is a calibration or unit problem until proven otherwise.
Scatter plots: pairs of columns and labels
A scatter plot of two features, coloured by the label, shows whether classes separate, whether they overlap, and whether individual points sit in the "wrong" cloud, which are candidates for label errors:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
iris = load_iris()
X, y = iris.data, iris.target.copy()
y[[60, 120]] = [0, 0] # two deliberately wrong labels
fig, ax = plt.subplots(figsize=(5, 4))
for k, marker in zip(range(3), ["o", "s", "^"]):
m = y == k
ax.scatter(X[m, 2], X[m, 3], marker=marker, alpha=0.7, label=iris.target_names[k])
ax.set_xlabel("petal length (cm)")
ax.set_ylabel("petal width (cm)")
ax.legend()
fig.tight_layout()
plt.show()
setosa_petal = X[y == 0, 2]
print("petal lengths labelled setosa: min", setosa_petal.min(), "max", setosa_petal.max())
print("setosa-labelled flowers with petals longer than 2.5 cm:", np.flatnonzero((y == 0) & (X[:, 2] > 2.5)).tolist())petal lengths labelled setosa: min 1.0 max 5.7
setosa-labelled flowers with petals longer than 2.5 cm: [60, 120]
Two "setosa" points sit in the middle of the other species, far from every real setosa: the plot points straight at the two flipped labels. With thousands of points, use transparency (alpha) or smaller markers so that dense areas do not hide each other, and plot a random sample if needed.
Looking at high-dimensional data
A dataset with 64 features (the 8-by-8 pixels of the digits) cannot be plotted directly. Principal component analysis (PCA) finds the directions in which the data varies most and projects the data onto them. The lab shows the idea in two dimensions: it turns a correlated cloud onto its principal axes and then, with one component, drops every point onto the first axis.
With the default correlation of 0.8, the first component keeps 90.8% of the variance ( of a total of ), so dropping to one dimension loses little. Set the correlation to 0 and the first component explains only 57.0%: when features are unrelated, no single direction summarises them. The Mathematics for ML course derives PCA, and Data Preparation uses it as a tool.
For visualisation, PCA to two components gives a first map of a high-dimensional dataset:
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
digits = load_digits()
pca = PCA(n_components=2, random_state=0)
Z = pca.fit_transform(digits.data)
fig, ax = plt.subplots(figsize=(5.5, 4.5))
sc = ax.scatter(Z[:, 0], Z[:, 1], c=digits.target, cmap="tab10", s=8, alpha=0.7)
fig.colorbar(sc, ax=ax, label="digit")
ax.set_xlabel("PC 1")
ax.set_ylabel("PC 2")
fig.tight_layout()
plt.show()
print("variance explained by 2 of 64 components:", pca.explained_variance_ratio_.round(3).tolist(),
"total", round(pca.explained_variance_ratio_.sum(), 3))variance explained by 2 of 64 components: [0.149, 0.136] total 0.285
Two components keep only 28.5% of the variance (14.9% and 13.6%), so the map is a rough sketch: the 0s, 4s and 6s occupy their own regions, while several other digits pile up in the middle, and an overlap in this picture does not mean the classes overlap in all 64 dimensions. Non-linear maps such as t-SNE and UMAP separate the digits much more clearly, but distort distances and cluster sizes, so they suit exploration rather than measurement.
Image grids: look at the samples
For images, audio and text, no statistic replaces looking at the samples themselves, a few dozen at random and a few dozen from each class. Grids make that fast:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
digits = load_digits()
rng = np.random.default_rng(0)
idx = rng.choice(len(digits.images), 24, replace=False)
fig, axes = plt.subplots(3, 8, figsize=(8, 3.4))
for ax, i in zip(axes.flat, idx):
ax.imshow(digits.images[i], cmap="gray_r")
ax.set_title(f"{digits.target[i]} (#{i})", fontsize=8)
ax.axis("off")
fig.suptitle("24 random digits with their labels")
fig.tight_layout()
plt.show()
print("shown:", sorted(idx.tolist())[:6], "...")shown: [4, 29, 72, 133, 312, 479] ...
Things to look for in an image grid: wrong labels, images that are blank, corrupted, rotated, cropped badly or not of the right kind at all (a photo of a screen, a test image), watermarks or text that give the label away, and differences between sources. Showing the sample index in each title lets you follow up on anything odd. Sorting the grid by the model's confidence (the most confident mistakes first) combines this with the label quality check.
Pitfalls
- One bin width: too few bins hide bumps, too many show noise. Try several.
- Extremes squashing the plot: plot the bulk; report placeholders and extremes separately; use a log scale for skewed data.
- Overplotting: thousands of opaque points hide density. Use transparency, small markers or a sample.
- Trusting 2-D maps: PCA keeps only part of the variance; t-SNE and UMAP distort distances.
- Never looking at the raw samples: a few minutes with an image grid or 50 random texts finds problems no statistic shows.
Practice
- A histogram of transaction amounts shows a tall spike at exactly 0.01 and another at 9,999.99. What might they be?
Answer
0.01 is typical of test or card-verification transactions; 9,999.99 looks like a system maximum or a placeholder. Both should be checked with the data owner and probably excluded from a model of real purchases.
- In the PCA lab, set the correlation to 0.95. How much variance does the first component explain, and what does that say about the two features?
Answer
97.9% (, ). The two features are almost redundant: one combination of them carries nearly all the information.
Test yourself
A weight histogram has a main peak around 70 and a smaller one around 155. The most likely cause is…
- Two species
- Some weights recorded in pounds
- Random noise
- Too many bins
What does a box plot draw as individual points?
- The mean
- Every value more than 1.5 IQR beyond the box
- The median
- Missing values
In a scatter plot coloured by label, a few points of class A sit deep inside the cloud of class B. What should you check?
- The plot's colours
- Whether those labels are wrong
- The number of bins
- The PCA variance
PCA to two components explains 28.5% of the variance of the digits. What does that mean for the 2-D plot?
- It shows the data perfectly
- It shows only part of the structure; classes that overlap in the plot may still be separable in 64 dimensions
- The data has only two features
- PCA failed