1.4.8 · D3Python & Scientific Computing

Worked examples — Matplotlib and Seaborn visualization

2,630 words12 min readBack to topic

You have met the parent note: Figure, Axes, ax.plot, histograms, log scales, coordinate transforms. This page does something different — it lists every kind of situation a plotting task can throw at you, then walks a worked example for each. The goal: when you sit at a real dataset, you never hit a case you have not already solved on paper.

Before we start, one promise of notation. A bin is one of the equal-width buckets a histogram slices the number line into. A KDE (kernel density estimate) is a smooth curve laid over those bars — we will build it from zero when we reach it. Everything else we define the moment it appears.


The scenario matrix

Think of plotting problems as a grid. Each row is a kind of question the data asks; each column is a twist that breaks a naive answer. If you can solve every cell, you can solve any real plot.

Cell Case class The twist you must survive
A One continuous variable Choosing bin count — too few hides structure, too many shows noise
B Two variables, correlation The sign of the slope (positive / negative / zero)
C Values spanning huge range Linear axis hides the tail → when to switch to log
D Degenerate input All values identical, or a single point, or empty array
E Categorical comparison Y-axis start point distorts small differences
F Coordinate placement Data coords vs axes coords for a caption
G Grouped distributions Comparing spread, not just centre (violin/box)
H Real-world word problem Translate a sentence into the right plot type
I Exam-style twist A plot that lies — spot and fix the distortion

The examples below are labelled with the cell(s) they cover. Together they touch every row.


Worked examples

Figure — Matplotlib and Seaborn visualization



Figure — Matplotlib and Seaborn visualization

Figure — Matplotlib and Seaborn visualization


Figure — Matplotlib and Seaborn visualization


Figure — Matplotlib and Seaborn visualization


Recall Quick self-test

A histogram of 400 points — square-root rule bin count? ::: bins. Regression slope is — positive, negative, or no relationship? ::: Effectively no relationship (slope ). Loss goes from to over training — linear or log y-axis? ::: Log — the range hides the tail on linear. A bar chart with y-axis starting at instead of — what's the danger? ::: It exaggerates small differences; the eye reads inflated pixel heights. ax.text(0.5, 0.5, s, transform=ax.transAxes) — where does the text go? ::: Dead centre of the Axes box, regardless of data range.

See also: 1.4.01-NumPy-arrays-and-operations for the arrays feeding these plots, 1.4.02-Pandas-DataFrames-and-data-manipulation for column-based Seaborn input, and 2.3.04-Confusion-matrix-and-classification-metrics for the heatmap cousin of these examples.