Level 3 In-Depth AI · Programming and Tools
Visualising Data
Charts show you what numbers hide. The Matplotlib and seaborn basics for histograms, scatter plots, box plots and training curves, and what to look for in each, so you catch bad data and failing models early.
- Level
- ●●●●● Beginner
- Reading
- 10 min
- To learn it well
- 45 minutes to read, an afternoon to practise
- Builds on
- 4 concepts →
- Quiz
- 5 questions ↓
Read first
NumPy and Array ThinkingThis leads to
—The full path from zero — 4 concepts before this one
Read them roughly in this order. See it on the concept map →
Why it matters
A table of a thousand numbers tells you almost nothing at a glance. A picture of the same numbers can tell you in one second that half the values are zero, that two groups overlap, that one measurement is a typo a thousand times too large, or that your model stopped learning after epoch 13.
Plotting is how you look at data before modelling it and how you watch a model while it trains. Experienced practitioners plot constantly. Andrej Karpathy's well-known recipe for training neural networks begins with "become one with the data", which mostly means looking at it. Almost every bug that a summary statistic hides, a plot reveals: a label column that leaked into the features, a broken preprocessing step, a learning rate that is too high.
This chapter teaches Matplotlib, the standard Python plotting library, and seaborn, a layer on top of it that makes statistical charts from Pandas and Working with Data DataFrames in one line. It covers the four chart types you will use most and, more importantly, what to look for in each.
The intuition
Each chart type answers one kind of question:
| Question | Chart |
|---|---|
| How are the values of one variable spread out? | Histogram |
| How do two variables relate? | Scatter plot |
| How does something change over time or over training steps? | Line plot |
| How does a variable differ between groups? | Box plot (or bar chart of averages) |
Choosing the chart is choosing the question. If you don't know what question you are asking, start with a histogram of every column.
Matplotlib builds a chart in layers, like a painter. There is a figure, the whole canvas, which contains one or more axes, each an individual chart with its own x and y axis. You draw data onto an axes and then add labels, a title and a legend. The confusing name "axes" (not "axis") just means "one plot area".
How it works
The conventional imports are:
import matplotlib.pyplot as plt
import seaborn as sns # optional, for statistical charts
The basic pattern
Always start with plt.subplots, which returns the figure and its axes. Then call drawing methods on the axes:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 100)
fig, ax = plt.subplots(figsize=(6, 4)) # width, height in inches
ax.plot(x, np.sin(x), label="sin(x)")
ax.plot(x, np.cos(x), label="cos(x)", linestyle="--")
ax.set(xlabel="x", ylabel="value", title="Two waves")
ax.legend()
fig.savefig("waves.png", dpi=150) # or plt.show() in a script
In a notebook the figure appears under the cell automatically. In a script, plt.show() opens a window, and fig.savefig writes a file. plt.subplots(2, 3) gives a grid of six axes as a 2 × 3 NumPy and Array Thinking array, so axes[0, 1] is the top middle chart.
You will also see a shorter style that calls plt.plot(...), plt.xlabel(...) directly, without naming the figure and axes. It works for quick single charts, but the explicit fig, ax style scales better to several panels, and the Matplotlib documentation recommends it for anything more than a quick plot.
Histograms: the shape of one variable
A histogram splits the range of a variable into equal bins and draws a bar for how many values fall in each.
ax.hist(values, bins=30)
What to look for:
- The shape. One hump or two? Two humps (a bimodal distribution) often means two different groups are mixed together.
- Skew. A long tail to the right, as with incomes, prices or Titanic fares, suggests plotting on a log scale (where equal distances mean equal ratios, so 1, 10, 100 and 1,000 are evenly spaced) or transforming the values before modelling.
- Spikes. A tall bar at exactly 0, −1 or 999 is often a placeholder for "missing" that was never converted to a real missing value.
- Impossible values. Negative ages, probabilities above 1, a person 3 metres tall.
Try a few bin counts. Too few bins hide structure. Too many make noise look like structure.
Scatter plots: two variables together
A scatter plot draws one dot per example, with one variable on each axis:
ax.scatter(x, y, c=labels, s=8, alpha=0.5) # colour by class, small, see-through dots
What to look for:
- Relationship. Does
yrise withx? In a straight line (Linear Regression will work) or a curve? - Clusters. Do points form groups? Coloured by class, are the classes separate (an easy problem) or tangled (a hard one)?
- Outliers. An outlier is a point far from all the others. It may be an error, or the most interesting example in the dataset. Investigate before deleting.
- Overplotting. With thousands of points, dots hide each other. Use small dots,
alphafor transparency, or a 2-D histogram (ax.hexbin).
High-dimensional data, such as 64-pixel images, can be squashed to two dimensions with PCA and Dimensionality Reduction or t-SNE and UMAP and then scatter-plotted. That is what the middle panel in "In code" does.
Line plots: training curves
A line plot connects points in order. In AI its most important use is the training curve: loss (or accuracy) plotted against training step or epoch, for both the training data and a held-out validation set.
ax.plot(train_losses, label="training")
ax.plot(val_losses, label="validation")
ax.set_yscale("log") # losses often fall by orders of magnitude
Reading training curves is one of the most useful skills in machine learning. A few shapes cover most situations:
- Healthy: both curves fall and flatten, with a small gap between them.
- Overfitting: the training loss keeps falling but the validation loss bottoms out and rises. The model is memorising the training examples. Stop at the minimum, get more data or add Regularization: L1 and L2. See Overfitting and the Bias–Variance Tradeoff.
- Underfitting: both losses stay high. The model is too simple, has not trained long enough, or the learning rate is too low.
- Diverging or spiky: the loss jumps up or becomes
NaN. The learning rate is usually too high. - Noisy: loss per mini-batch jumps around. Plot a moving average as well, or the loss per epoch.
Box plots: comparing groups
A box plot summarises a variable within each group. The box spans the middle half of the values (from the 25th to the 75th percentile), the line inside is the median, the whiskers stretch to the typical range, and dots beyond them are outliers. With seaborn and a DataFrame it is one line:
df = sns.load_dataset("titanic") # downloads a small CSV the first time
sns.boxplot(data=df, x="pclass", y="fare")
sns.histplot(data=df, x="age", hue="survived", multiple="stack")
The first line shows that first-class fares were far higher and far more spread out than third-class ones. The second stacks survivors on non-survivors for each age band, and reveals that most young children survived. Seaborn takes column names and does the grouping, colouring and legend for you, which is why it is popular for DataFrame exploration.
Key idea Plot before you model, and plot while you train. A histogram of every input column and a training curve with a validation line catch more bugs than any amount of staring at printed numbers.
In code
This complete script uses the small handwritten-digits dataset that ships with scikit-learn (1,797 images of 8 × 8 pixels), so it runs offline. It draws a histogram, a scatter plot and real training curves from a small neural network, then saves the figure.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import log_loss
from sklearn.decomposition import PCA
X, y = load_digits(return_X_y=True) # 1,797 8x8 images of digits
X_tr, X_val, y_tr, y_val = train_test_split(X / 16, y, test_size=0.8, random_state=0)
# Train a small network one epoch at a time and record both losses.
net = MLPClassifier(hidden_layer_sizes=(64,), learning_rate_init=0.03, random_state=0)
train_loss, val_loss = [], []
for epoch in range(100):
net.partial_fit(X_tr, y_tr, classes=np.arange(10))
train_loss.append(log_loss(y_tr, net.predict_proba(X_tr)))
val_loss.append(log_loss(y_val, net.predict_proba(X_val)))
fig, axes = plt.subplots(1, 3, figsize=(13, 3.6))
axes[0].hist(X[:, 36], bins=17, color="tab:blue") # one pixel's brightness
axes[0].set(title="Histogram: pixel 36", xlabel="brightness (0-16)", ylabel="count")
Z = PCA(n_components=2).fit_transform(X) # squash 64 pixels to 2 numbers
sc = axes[1].scatter(Z[:, 0], Z[:, 1], c=y, cmap="tab10", s=8)
axes[1].set(title="Scatter: digits in 2-D (PCA)", xlabel="component 1", ylabel="component 2")
fig.colorbar(sc, ax=axes[1], label="digit")
axes[2].plot(train_loss, label="training")
axes[2].plot(val_loss, label="validation")
axes[2].set(title="Training curves", xlabel="epoch", ylabel="log loss", yscale="log")
axes[2].legend()
fig.tight_layout()
fig.savefig("digits_plots.png", dpi=150)
best = int(np.argmin(val_loss))
print(f"best epoch {best}: val loss {val_loss[best]:.3f}, final val loss {val_loss[-1]:.3f}")
print(f"final train loss {train_loss[-1]:.4f}")
# best epoch 13: val loss 0.181, final val loss 0.223
# final train loss 0.0008
Look at the saved picture. The histogram shows pixel 36 piles up at the two extremes, blank (0) and fully inked (16), with the remaining values spread thinly in between. The scatter shows that even squashed to two numbers, some digits (0, 4, 6) form clear clusters while others overlap. The training curves show textbook overfitting: the network trains on only 359 images, its training loss keeps falling towards zero, but its validation loss is lowest at epoch 13 and then creeps up. Everything after epoch 13 is memorisation.
Common pitfalls
- Unlabelled axes. A chart without axis labels and units is a puzzle. Label everything, including the y-axis of training curves ("loss", and which loss).
- Misleading axes. A y-axis starting at 0.95 makes a 1% difference look huge. Know when your axis starts, and say so if it isn't zero.
- Linear scale for skewed data. A few huge values squash everything else into one bar. Try
ax.set_xscale("log"). - Only plotting training loss. Training loss always looks good eventually. Without a validation curve you cannot see overfitting.
- Colour that only some people can see. About one in twelve men has some form of colour-vision deficiency, most often red–green. Use colour-blind-safe palettes (Matplotlib's default
tab10andviridisare reasonable) and different line styles as well as colours. - Too many figures. In a loop, call
plt.close(fig)after saving, or memory fills up with hundreds of open figures.
Watch out Summary statistics can be identical for completely different data. Anscombe's quartet is four small datasets with the same means, variances, correlation and best-fit line, yet one is a clean line, one a curve, and two are dominated by a single outlier. Never trust a correlation or average you have not plotted.
Where it leads
- scikit-learn and Evaluation Metrics add specialised plots: confusion matrices, ROC curves and precision–recall curves.
- Experiment Tracking and Reproducibility tools such as TensorBoard and Weights & Biases draw training curves live, for many runs at once.
- PCA and Dimensionality Reduction and t-SNE and UMAP make scatter plots of high-dimensional data such as Word Embeddings.
- For interactive charts in a browser, Plotly and Altair are popular alternatives built on the same ideas.
A bit of history
John D. Hunter, a neurobiologist, wrote Matplotlib in 2003 because he wanted MATLAB-style plotting in Python for analysing brain recordings. That heritage is why plt.plot looks like MATLAB. Hunter died in 2012, and the project has been maintained by a community of volunteers since. Michael Waskom created seaborn around 2012 while a graduate student in neuroscience, to make statistical graphics from DataFrames simpler. The statistician Francis Anscombe published his famous quartet in 1973 to argue that graphs are essential to good statistical analysis, and William Playfair had invented the line chart and bar chart back in 1786.
Try it
- Run the script with
test_size=0.5(more training data). How does the gap between the two curves change, and at which epoch is validation loss lowest now?- Plot a histogram of every column of the Titanic data with
df.hist(figsize=(12, 8)). Which columns are skewed, and which have suspicious spikes?- Make the learning rate
1.0in the script and look at the training curve. Which of the four shapes does it resemble?Hint for 1: with 898 training images instead of 359, overfitting starts later and is milder. Hint for 3: the loss stays near 2, close to the log loss of guessing at random among ten classes (ln 10 ≈ 2.3). A learning rate far too high can look like underfitting, because the weights jump around instead of settling.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Matplotlib Quick Start Guide
The official introduction to figures, axes, the explicit fig/ax style and the most common plot types.
seaborn tutorial
The official user guide to statistical plots from DataFrames: distributions, relationships, categories and themes.
Python Data Science Handbook
Free online book covering IPython and notebooks, NumPy, pandas, Matplotlib and scikit-learn, every chapter a runnable notebook.
Kaggle Learn: Data Visualization
A short hands-on course on line charts, bar charts, heatmaps, scatter plots and distributions with seaborn.
Fundamentals of Data Visualization
A free book on choosing the right chart and making it clear and honest, independent of any software.
Matplotlib cheatsheets and handouts
Printable one-page summaries of Matplotlib's plot types, styles and options.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/programming/plotting.md