Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 57 ยท Working with Data

Seaborn-Style Recipes in Pure Matplotlib

Rebuild pair plots, KDE curves, regression plots, strip plots and joint plots with Matplotlib, SciPy and GridSpec, and see what seaborn shortens.

Seaborn is a popular library built on Matplotlib that turns common statistical charts into one-liners. It is not available in the browser runner on this site, but you do not need it to learn what it does. Every seaborn chart is made of ordinary Matplotlib parts: scatter plots, lines, histograms and filled areas. Building them yourself teaches you what the one-liners hide, and the recipes work anywhere Matplotlib does.

In this lesson you rebuild five seaborn-style charts: a pair plot, smooth density curves, a regression plot with a confidence band, strip plots with jitter and a joint plot made with GridSpec. Each recipe ends with the seaborn call you would use in your own environment; those snippets are read-only. Data is generated with fixed seeds so the pictures are repeatable.

Recipes in this lesson

Pair plot Every column against every column.
Density curves Smooth histograms with SciPy.
Regression plot Fit line plus uncertainty band.
Strip plot Points by category, jittered.

Plus a joint plot built from GridSpec.

1 / 2

A shared dataset

All recipes use one small synthetic dataset of 150 penguin-like measurements in three species. Species differ in the mean of each measurement, so the charts have something to show.

Python Create and inspect the dataset

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

You will see 150 rows and 4 columns, with the per-species means close to the numbers chosen above. The later recipes repeat these few lines so each TryIt runs on its own.

Recipe 1: a pair plot

A pair plot shows every numeric column against every other column in a grid, with the distribution of each column on the diagonal. In Matplotlib that is plt.subplots(n, n) and a double loop, with a histogram when the row and column are the same.

Python A pair plot from a double loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Row i supplies the y variable and column j the x variable, so the diagonal (i == j) is where a variable meets itself and a histogram makes sense. You could also hide the upper triangle, which repeats the lower one.

Read-only, the seaborn version:

Python
import seaborn as sns

sns.pairplot(df, hue="species")

Recipe 2: density curves with SciPy

A histogram depends on bin choices. A kernel density estimate (KDE) replaces the bars with a smooth curve: each observation contributes a small bell, and the bells add up. SciPy's gaussian_kde does the math; you evaluate it on a grid and plot the result. fill_between gives the shaded look.

Python KDE curves per species

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Each area prints very close to 1 (0.99 to 1.00): a density is scaled so the total area equals 1, which makes curves comparable even when groups have different sizes. A KDE has a bandwidth, the width of each bell. Pass bw_method=0.3 (smaller is wigglier) or a larger number (smoother) to gaussian_kde; the default is a sensible rule of thumb.

Seaborn version (read-only):

Python
sns.kdeplot(data=df, x="bill_length", hue="species", fill=True)

Recipe 3: a regression plot with a confidence band

sns.regplot draws a scatter plot, a fitted line and a shaded band showing how uncertain the line is. You can rebuild it with np.polyfit for the line and bootstrapping for the band: refit the line on many resamples of the data and take the spread of the predictions.

Python Scatter, fit line and bootstrap band

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The band is narrowest near the middle of the data and wider at the edges, because a line pivots around the center of mass of the points. The printed fit is close to the true slope of 2 and intercept of 5, with some noise. More resamples give a smoother band at the cost of time; 500 is plenty for a picture.

Seaborn version (read-only):

Python
sns.regplot(x=x, y=y, ci=95)

Recipe 4: strip plots and swarms

Box plots hide the individual points. A strip plot shows every observation for each category and adds a little random horizontal jitter so points do not sit on top of one another. A swarm plot moves points sideways just enough to avoid overlap; the same effect can be approximated with jitter scaled to the local density. Combining a strip with a mean marker is a clean, honest alternative to a bar chart.

Python Jittered strip plot with means

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Categories live at integer x positions 0, 1, 2 and set_xticks gives them names. The jitter only moves points horizontally, so the vertical position, the real data, is untouched. Never jitter the axis that carries the measurement.

Seaborn version (read-only):

Python
sns.stripplot(data=df, x="species", y="flipper", jitter=0.2)
sns.swarmplot(data=df, x="species", y="flipper")

Recipe 5: a joint plot with GridSpec

sns.jointplot pairs a central scatter plot with the distribution of each variable in margins along the top and right. In Matplotlib you build that layout with GridSpec: a 4 by 4 grid where the scatter takes the lower-left 3 by 3 block, and thin margin Axes sit above and to the right. Sharing axes keeps the margins aligned with the scatter (GridSpec and subplot_mosaic covers the layout tools).

Python Scatter with marginal histograms

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The printed-in-chart correlation r is about 0.65 for this data. sharex=ax_main means zooming or setting limits on the main plot moves the margin too. Using transform=ax_main.transAxes places the text at a fraction of the Axes, independent of the data range.

Seaborn version (read-only):

Python
sns.jointplot(data=df, x="bill_length", y="flipper", kind="scatter")

Recipe 6: a count plot and a pandas scatter matrix

Seaborn's countplot draws one bar per category, with the bar height equal to the number of rows. There is nothing statistical about it: it is value_counts() plus a bar chart. For a second grouping variable (hue=) the bars are placed side by side, which is called dodging. The data here has the species and a new column, "size class", cut from the flipper length.

Pandas also has a ready-made pair plot, pd.plotting.scatter_matrix, which draws the same grid as Recipe 1 in a single call. It returns the array of Axes, so you can still polish them.

Python countplot by hand, and scatter_matrix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The crosstab is the table behind the grouped bars, and bar_label writes the counts on top of each bar. scatter_matrix gives a 3 by 3 grid, with histograms on the diagonal (use diagonal="kde" for density curves).

Recipe 7: a facet grid

sns.FacetGrid and sns.lmplot split the data into small multiples: one panel per group, all with the same axes so the panels are directly comparable. In Matplotlib, make the grid with plt.subplots(1, n, sharex=True, sharey=True) and loop over the groups. Sharing the axes is the important part: with different ranges per panel, the eye cannot compare them.

Python Small multiples with a regression line per species

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

For a grid in both directions (rows by one variable, columns by another), use plt.subplots(nrows, ncols, sharex=True, sharey=True) and index axes[i, j], or let subplot_mosaic name the panels.

Recipe 8: a smoother instead of a straight line

sns.regplot(..., lowess=True) fits a LOWESS curve (locally weighted regression), which follows bends in the data where a straight line cannot. The idea is simple: for each x, fit a straight line to the nearest points only, weight closer points more with a tricube kernel, and read off the fitted value. The result is a smooth curve whose flexibility is set by the fraction frac of the data used for each local fit. Here is a small version in NumPy; the statsmodels package has an optimized lowess if you need one with robustness iterations.

Python LOWESS smoother in NumPy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A small frac follows the data closely (and the noise); a large one gives a smooth curve that may miss real bends. The straight line misses the wave in this data entirely, which is the point of the smoother.

Seaborn versions of these three recipes (read-only):

Python
sns.countplot(data=df, x="species", hue="size_class")
sns.lmplot(data=df, x="bill_length", y="flipper", col="species")
sns.regplot(data=df, x="bill_length", y="flipper", lowess=True)

What seaborn shortens, and what it costs

Task Matplotlib recipe Seaborn
Pair plot Double loop over subplots sns.pairplot
Group colors groupby loop and a color dict hue="species"
Density curve gaussian_kde + fill_between sns.kdeplot
Regression band polyfit + bootstrap + fill_between sns.regplot
Strip or swarm Jitter by hand sns.stripplot, sns.swarmplot
Joint plot GridSpec with shared axes sns.jointplot
Count plot value_counts or crosstab + bar sns.countplot
Facet grid subplots(sharex, sharey) + loop sns.FacetGrid, sns.lmplot
Smoother local weighted fit in NumPy sns.regplot(lowess=True)

Seaborn wins on speed and defaults. Matplotlib wins when you need an unusual layout, need to add custom annotations or want one fewer dependency. The two cooperate: seaborn functions return Matplotlib Axes (or small wrapper objects around them), so you can start with a seaborn call and finish with ax.set_title and ax.annotate. Later, The Matplotlib Ecosystem compares seaborn with other libraries.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In the pair plot loop, what is drawn on the diagonal (i == j)?

    A scatter of a variable against itself is just a diagonal line, so pair plots show the variable's distribution there instead.
  2. 2. Why does the total area under a KDE curve come out near 1?

    A kernel density estimate is a probability density, so by definition its integral over all values is 1. That makes groups of different sizes comparable.
  3. 3. How does the recipe produce the confidence band of the regression line?

    Resampling the points with replacement, refitting and taking the 2.5th and 97.5th percentiles of the predicted lines gives a 95% bootstrap band.
  4. 4. In a strip plot, which axis should receive jitter?

    Jitter spreads overlapping points sideways along the category axis. Moving the measurement axis would change the data being shown.
  5. 5. What does sharex=ax_main do for the top marginal histogram in the joint plot?

    Sharing the x axis links the limits and scale, so bars line up with the points directly below them.

Summary

  • Seaborn charts are built from ordinary Matplotlib parts, so you can rebuild them when seaborn is not available.
  • A pair plot is a subplots(n, n) grid with a double loop; the diagonal shows distributions.
  • scipy.stats.gaussian_kde plus fill_between gives smooth density curves; the area under each is 1.
  • np.polyfit plus bootstrap resampling gives a regression line with a confidence band.
  • Strip plots add horizontal jitter to category scatter plots; never jitter the measured axis.
  • GridSpec with shared axes builds a joint plot with marginal histograms.
  • Seaborn is shorter and has good defaults; Matplotlib gives full control, and the two combine.

Next: Statistical Plots Recipes