09

Chapter 9 · Python

Python: Seaborn

Matplotlib draws what you tell it to draw. Seaborn is told what you want to know, and works out the statistics and the styling itself. It sits on top of Matplotlib, so you keep everything from Weeks 7 and 8 and gain a statistical layer above it.

1Matplotlib against Seaborn

MatplotlibSeaborn
LevelLow, very flexibleHigh level interface
Data inputArrays and lists, subset manuallypandas DataFrame passed as data=
SyntaxVerboseConcise
StatisticsManual, you compute the mean yourselfBuilt in, means and confidence intervals automatic
AestheticsBasic defaultsPleasing defaults
PurposeFull customisationStatistical visualisation
Fig 9.1The same scatter, written both ways

Seaborn takes the whole DataFrame and you name columns as strings, with no manual subsetting. Axis labels appear automatically from the column names, which matters even during exploration because you always know what you are looking at.

The statistics difference

Fig 9.2What sns.barplot does that you did not ask for

Three things unasked: it computes the mean per category, draws confidence intervals as error bars showing how much the average could vary given the sample size, and orders the bars sensibly. That third point matters more than it looks, because Chapter 4 said assembly and estimation are what make a chart readable and an unordered bar chart blocks both.

Combining the two

sns.boxplot(data=df, x='course', y='exam_score')          # Seaborn draws
plt.title('Exam Scores by Course')                        # Matplotlib customises
plt.ylabel('Final Score')
plt.axhline(df['exam_score'].mean(), color='r', linestyle='--')
plt.show()

The standard working pattern: Seaborn for the main visual, Matplotlib for titles, reference lines and annotations.

A horizontal average line added this way turns a distribution chart into a comparison against a benchmark, which is Chapter 5's "context makes a number meaningful".

Matplotlib remains the core library for exploration. Seaborn is what you reach for when the chart goes into a report or a dashboard.

The architectural idea: figure-level and axes-level

This is the concept that makes Seaborn make sense, and the one most people miss.

Fig 9.3Which functions own the figure, and which do not

Use axes-level when you are assembling a figure yourself and want the plot in a specific panel. Use figure-level when you want Seaborn to build a grid of small multiples for you. Each figure-level function is a wrapper over a family of axes-level ones, so relplot(kind='line') gives you lineplot with faceting on top.

Semantic mappings: hue, style, size

The core Seaborn idea. Instead of drawing several series manually, you name a column and Seaborn maps it to a visual channel.

Fig 9.4Add one channel at a time to the tips data

Combine hue and style for the same variable and the distinction becomes much easier to read, because colour alone makes the brain process an extra layer while different shapes make the grouping immediate through the similarity principle. Map them to different variables and one plot carries four dimensions: x, y, colour and shape.
Print warning

hue and style are vivid on screen and much weaker in black and white. If the chart will be printed, do not rely on colour alone. This is Chapter 3's accessibility rule. sizes=(15, 200) sets a custom size range and Seaborn scales the data into it, and without it raw values may produce unreadable markers.

Line plots and statistical aggregation

Fig 9.5The band around the line, and what turning it off shows

When several observations share an x value, lineplot aggregates them into a mean automatically. The shaded band is the confidence interval, and its width tells you how dispersed the underlying values are at that point. A wide band means dispersed data, a narrow one means tightly packed. That turns a plain line into a statistical statement: you see both the trend and how much to trust it.

Faceting: small multiples, automatically

Fig 9.6col= and row= build the grid for you
This is small multiples from Chapter 2, generated automatically. Four categories crammed into one plot need real effort to untangle, and the same four as a 2×2 grid read instantly. The reasoning is Chapter 3's: reduce the cognitive load on the audience, and faceting is the cheapest way to do it.

Categorical plots

All reachable through catplot(kind=...) or as individual axes-level functions.

Fig 9.7The whole family, on one dataset

Jitter exists because overlapping points hide the count. Ten identical values plot as one dot, and jitter offsets them slightly so the density becomes visible, at the cost of exact position. Swarm does the same thing deterministically. This is the distribution ladder from Chapter 1, now as Seaborn commands: box shows summary, boxen shows more, swarm shows everything.

Distributions

FunctionPurpose
histplotUnivariate distribution as bars
kdeplotSmoothed density estimate
ecdfplotCumulative distribution
rugplotTicks marking individual observations
jointplotBivariate scatter with both marginal distributions on the axes
pairplotEvery variable against every other
Fig 9.8jointplot and pairplot, the Chapter 1 and Chapter 2 charts in one command

jointplot is the joint plot from Chapter 1: a scatter with the distribution of x and y drawn along the axes, so you can check whether a relationship holds across the whole range or only part of it. pairplot is the scatter plot matrix from Chapter 2 in one command, and it is the fastest exploratory sweep over a new dataset. displot is the figure-level wrapper that adds faceting to these.

Regression plots

Regression estimates how much an independent variable influences a dependent one. The course is not teaching the statistics, it is teaching how to present the result so an audience accepts it.

regplotlmplot
LevelAxesFigure
Data formatMore flexiblex and y must be column-name strings
Supports hue, col, rowNoYes
Fig 9.9One regression, then one per group

Use lmplot when you want separate regressions per group. The regression line does not pass through every point, it captures the overall relationship among them. In the tips data, total bill is the independent variable and tip the dependent one, because the bill influences the tip and not the reverse. Getting this the right way round is the analyst's job, not the software's.
ArgumentEffect
ci=NoneRemoves the confidence band around the line
scatter_kws={'s': 80}Sets the size of the scattered points
order=2Fits a polynomial of that degree instead of a straight line

Anscombe's quartet, revisited

Fig 9.10The model does not tell you it is the wrong model. The plot does

Chapter 1 used Anscombe's quartet to prove that summary statistics hide shape. Chapter 9 uses it to prove the same about regression models. Dataset II is a parabola, a straight line still gets drawn and still reports a fit, and it is wrong. Setting order=2 fits the curve properly. That is the argument for visualising every regression before reporting it, and it is the same conclusion as Chapter 8's polynomial-against-linear forecast.

Key points

  1. Six differences between Matplotlib and Seaborn.
  2. Why sns.barplot needs one line where Matplotlib needs a groupby.
  3. The three things barplot does automatically, including ordering.
  4. The working pattern of Seaborn for the visual and Matplotlib for the finishing.
  5. Figure-level against axes-level functions, with examples of each.
  6. Why only figure-level functions can facet.
  7. hue, style and size, and why combining hue and style helps.
  8. Why colour alone fails in print.
  9. How lineplot aggregates, and what the shaded band means.
  10. What estimator=None does.
  11. col= and row= faceting, and its link to small multiples.
  12. Why jitter and swarmplot exist.
  13. The categorical plot family, and which shows summary against every point.
  14. jointplot and pairplot, and their equivalents from Weeks 1 and 2.
  15. regplot against lmplot, and when the difference matters.
  16. What ci=None and order=2 do.
  17. The Anscombe regression demonstration, and why every model should be plotted.