Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Appendix E — Seaborn tutorial

In this tutorial, we’ll learn about the seaborn library for data visualizations. We’ll start by explaining the plotting function interface that is common to all seaborn functions, then list all the seaborn functions thought examples. We’ll also describe the various options for customize plots’ the appearance, add adding annotations and labels.

Click the binder button Binder or this link bit.ly/4twDwZu to play with the tutorial notebook interactively.

Notebook setup

Before we begin the tutorial, we we must take care of some preliminary tasks to prepare the notebook environment. Feel free to skip this commands

Installing seaborn and other libraries

We can install Python package pandas in the current environment using the %pip Jupyter magic command.

Note: you may need to restart the kernel to use updated packages.

Setting display options

Next, we run some commands to configure the display of figures and number formatting.

Download datasets

The ministats package provides a helper function for downloading datasets. We’ll use this function now to make sure the datasets/ folder that accompanies this tutorial is present.

datasets/ directory present and ready.

With all these preliminaries in place, we can now get the pandas show started!

Loading datasets

Loading...

Seaborn overview

The seaborn library is a powerful toolbox for generating statistical data visualizations. Seaborn makes it very easy to visualize data stored in pandas data frames. You can generate standard statistical plots like barplots, stripplots, scatterplots, using just a few lines of code. If you plan to pursue a career in a data-related field, learning a bit about seaborn is highly recommend.

Learning objectives

In this tutorial, I’m going to show you how to ...

Seaborn line plots

We’ll start by playing with the seaborn function for generating line plots sns.lineplot. We’ll use this function to learn the the syntax for mapping data to graph attributes, which is common to all seaborn plotting function.

Simple line plot

<Axes: xlabel='x', ylabel='y'>
<Figure size 500x170 with 1 Axes>

Line plot with statistical calculations

Loading...
<Axes: xlabel='week', ylabel='weight'>
<Figure size 500x170 with 1 Axes>

Pandas datasets

The iris dataset

Loading...

The tips dataset

Loading...

The students dataset

Loading...
<Axes: xlabel='effort', ylabel='score'>
<Figure size 500x170 with 1 Axes>

Inventory of seaborn plotting functions

Strip plots

Use the function sns.stripplot

<Figure size 500x170 with 1 Axes>
<Figure size 600x100 with 1 Axes>

ALT. sns.swarmplot or sns.rugplot

Point plots

Use the function sns.pointplot

Scatter plots

Use the function sns.scatterplot

Line plot

Use the function sns.lineplot

Histograms

Use the function sns.histplot

Kernel density plots

Use the function sns.kdeplot

Box plots

Use the function sns.boxplot

Violin plots

Use the function sns.violinplot

Empirical Cumulative Distribution Function (ECDF) plot

Use the function sns.ecdfplot

Count plot

Use the function sns.countplot

<Axes: xlabel='class', ylabel='count'>
<Figure size 500x170 with 1 Axes>
Loading...
<Figure size 500x170 with 1 Axes>
<Axes: xlabel='class', ylabel='count'>
<Figure size 500x170 with 1 Axes>

Bar plots

Use the function sns.barplot

Plotting function graphs

<Figure size 500x170 with 1 Axes>

Linear model plots

Linear regression plot

<Figure size 500x170 with 1 Axes>

Residuals plot

<Figure size 500x170 with 1 Axes>

Linear model plots from scratch

Linear model plots using statsmodels

Plotting probability distributions

Line plots for continuous random variables

Stem plots for discrete random variables

Customizing plots

Anotomy of a figure

<Figure size 800x800 with 1 Axes>

Adding text annotations

<Figure size 500x170 with 1 Axes>
<Figure size 500x170 with 1 Axes>
Country Canada 2020 France 2020 Germany 2020 Great Britain 2020 Japan 2020 USA 2020 Name: Year, dtype: int64

Layout options

optionmeaningvalues / exampleapplies to
colorsingle colour override"k"sca, lin, his, kde, ecdf, str, swa, box, vio, poi, bar, cnt, reg, res
orientvertical/horizontal"v"/"h" or "x"/"y"lin, str, swa, box, vio, poi, bar, cnt
dodgeseparate hue groupsTrue/False/"auto"his, str, swa, box, vio, poi, bar, cnt
jitterrandom x spreadTrue, 0.2str
widthelement width0.8box, vio, bar, cnt
log_scalelog axesTrue, 10, (True, False)his, kde, ecdf, str, swa, box, vio, poi, bar, cnt

Matplotlib pass-through options

Seaborn plot functions will “forward” keywords arguments to the underlying matplotlib plotting function. This means we can sometimes use certain matplotlib options to change plot appearance.

optionmeaningvalues / exampleapplies to
alphatransparency0.3sca, lin, his, kde, ecdf, str, swa, box, vio, poi, bar, cnt, reg, res, hea
colorsingle colour override"k"sca, lin, his, kde, ecdf, str, swa, box, vio, poi, bar, cnt, reg, res
linewidthline/edge width1.5sca, lin, his, kde, ecdf, str, swa, box, vio, poi, bar, cnt, reg, res, hea
linestyle/linestylesline style"-", "--"lin, kde, ecdf, poi, reg
markermarker style"o", ".", dictsca, lin, str, swa, poi, reg, res
smarker areas=30scatterplot, stripplot, swarmplot
labellegend labellabel="controls"

Advanced seaborn topics

Seaborn figure-level functions (FacetGrid objects)

<Figure size 500x170 with 2 Axes>

Alternatively, we can use sns.displot with curriculum as the row option to produce a similar plot.

<Figure size 740.375x400 with 2 Axes>

Data visualization tips

Here are some links to learning resources for seaborn and data visualization techniques.

Official docs

[ Seaborn documentation website ]
https://seaborn.pydata.org/
https://seaborn.pydata.org/introduction.html

[ Seaborn tutorials featuring lots of useful plot examples ]
https://seaborn.pydata.org/tutorial.html

[ Gallery of data visualizations produced using seaborn ] https://seaborn.pydata.org/examples/index.html

Tutorials

[ Seaborn tutorial for beginners ]
https://www.datacamp.com/community/tutorials/seaborn-python-tutorial

[ The ultimate Python seaborn tutorial ]
https://elitedatascience.com/python-seaborn-tutorial

[ Seaborn Tutorial ]
https://www.geeksforgeeks.org/python-seaborn-tutorial/

Video tutorials

[ Intro to seaborn by Kimberly Fessel (excellent!) ]
https://www.youtube.com/playlist?list=PLtPIclEQf-3cG31dxSMZ8KTcDG7zYng1j
see also notebooks from the videos.

[ Seaborn Tutorial 2021 by Derek Banas ]
https://www.youtube.com/watch?v=6GUZXDef2U0

[ Data Visualisation with seaborn Crash Course by Valentine Mwangi ]
https://www.youtube.com/watch?v=zafPvR4MmBA
See also the colab notebook for the course.

Other plotting libraries:

CUT MATERIAL

Note: you may need to restart the kernel to use updated packages.
Loading...
<seaborn.axisgrid.FacetGrid at 0x1151d2f30>
<Figure size 988.375x600 with 2 Axes>
Loading...

FMRI

Loading...
<Figure size 500x170 with 1 Axes>
(244, 7)
Loading...

The Dow Jones dataset

<Axes: xlabel='Year', ylabel='Price'>
<Figure size 500x170 with 1 Axes>
<Figure size 500x300 with 1 Axes>