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.

Introducing Seaborn

DS 2023 | Communicating with Data

Overview

Seaborn is visualization library written in Python and built on top of Matplotlib.

According to its website, Seaborn “provides a high-level interface for drawing attractive and informative statistical graphics.”

Seaborn provides three programming interfaces for creating visualizations:

Axes-Level Functions:

  • Functions include sns.barplot(), sns.scatterplot(), sns.histplot(), sns.boxplot(), etc.

  • These plot data onto a single Matplotlib Axes object and return that Axes.

  • They integrate smoothly into pre-existing multi-panel Matplotlib figures.

  • Many of these functions are drop-in replacements for Pandas’ plot types.

Figure-Level Functions:

  • Functions include sns.relplot(), sns.displot(), and sns.catplot().

  • These three functions group together the Axes plot types into Figure level functions.

  • They manage an entire figure using a Seaborn container object (usually a FacetGrid).

  • They easily generate multi-plot grids (small multiples) and control layout properties like legend placement at the figure level.

The Object-Oriented Interface:

  • A modular system is inspired by the Grammar of Graphics.

  • It initializes with the so.Plot() constructor and builds graphics incrementally.

  • Variables are mapped to visual Mark layers (e.g., so.Dot(), so.Bar()).

Pandas vs. Seaborn Interfaces Mapping Table

Plot TypePandasSeaborn AxesSeaborn FigureSeaborn Object
Scatter Plotdf.plot.scatter()sns.scatterplot()sns.relplot(kind="scatter")so.Plot().add(so.Dot())
Line Plotdf.plot.line()sns.lineplot()sns.relplot(kind="line")so.Plot().add(so.Line())
Histogramdf.plot.hist()sns.histplot()sns.displot(kind="hist")so.Plot().add(so.Bar(), so.Hist())
KDE Plotdf.plot.kde()sns.kdeplot()sns.displot(kind="kde")so.Plot().add(so.Line(), so.KDE())
Box Plotdf.plot.box()sns.boxplot()sns.catplot(kind="box")so.Plot().add(so.Box())
Bar Plotdf.plot.bar()sns.barplot()
sns.countplot()
sns.catplot(kind="bar")
sns.catplot(kind="count")
so.Plot().add(so.Bar())

Seaborn’s design philosophy

Seaborn is an opiniated graphics library.

It is designed to produce statistical plots from Tidy data as efficiently and as clearly as possible.

To do this, it shields the user from many of the data transformations that we have learned, like creating wide-form data and applying aggregate functions.

Axes level functions

In this notebook, we will focus on Seaborn’s Axes level functions.

These are, for the most part, drop-in replacements for the same functions in Pandas and Matplotlib.

Bar plots

Let’s begin with bar plots, using the Penguins dataset.

Loading...

To create a bar plot showing the counts of a category variable, we can first compute the value_counts and then plot them directly.

species Adelie 146 Gentoo 119 Chinstrap 68 Name: count, dtype: int64
<Figure size 640x480 with 1 Axes>

Count plots

Plots that show counts like this are so common that Seaborn provides a dedicated function for it called countplot.

The countplot function automatically does the value counting for you.

<Figure size 640x480 with 1 Axes>

Note the change in sort order of the category names, though.

It defaults to alphabetical order.

To change the order, you have to set the order parameter yourself, like so:

<Figure size 640x480 with 1 Axes>

Notice how this breaks Seaborn’s principle of abstracting low-level data operations from the user.

Back to bar plots

Seaborn will also plot bars for any measurement variable against a grouping variable.

<Figure size 640x480 with 1 Axes>

In creating this plot, Seaborn assumes you want to aggregate the value of the measurement variable against the grouping one.

By default, it computes the mean.

You can change the aggregation function using the estimator parameter to median, std, sum, etc.

<Figure size 640x480 with 1 Axes>

If you don’t want to have the error calculated and show the bars, set errorbar=None.

<Figure size 640x480 with 1 Axes>

Two grouping variables

To show a second grouping variable, just set hue to that variable.

Seaborn handles the data transformation for you.

<Figure size 640x480 with 1 Axes>

You can use hue on count plots, too.

<Figure size 640x480 with 1 Axes>

Pie charts

Seaborn doesn’t do pie charts.

Line plots

To create a line plot, you pass series data to the x and y parameters.

Loading...
<Figure size 640x480 with 1 Axes>

Using series or wide-form data

You can also pass a standalone Pandas series or a wide-form dataframe to a Seaborn Axes function.

In these cases, you don’t have to define explicit x or y variables.

Seaborn will default to using the index values as the x axis and the series columns for the y axis.

<Figure size 640x480 with 1 Axes>

Changing figure size

If you want to change the size of a Seaborn Axes level plot, you have to use Matplotlib.

This is true of all Axes level functions.

<Figure size 1000x600 with 1 Axes>

Using a grouping variable

Let’s look at an example where there is a grouping variable.

Loading...

Here, we plot the data without specifying the grouping variable month, even though without it, the years variable is repeated.

In this case, the line plot defaults to aggregating the observations that belong to the month variable.

<Figure size 640x480 with 1 Axes>

The shaded area represents the 95% confidence interval for the mean number of passengers spending across months in the dataset for a given year.

To show standard deviation instead of the confidence interval, change the value of errorbar to sd.

<Figure size 640x480 with 1 Axes>

Or, to lose the representation of error altogether, do this:

<Figure size 640x480 with 1 Axes>

To bypass aggregation and actually show lines for each value of the grouping variable month, we set hue to that variable.

<Figure size 640x480 with 1 Axes>

A more interesting plot in this case would be to set the hue to year and x to month.

<Figure size 640x480 with 1 Axes>

Notice that although Seaborn expects tidy data, you can also pass it a wide dataframe and it will (usually) know what to do.

Loading...
<Figure size 640x480 with 1 Axes>

Area charts

There are no area charts in Seaborn.

If you want them, you can fall back on Matplotlib’s fill_between since we are working with Seaborn’s Axes level functions.

Here is a worked out example.

<Figure size 640x480 with 1 Axes>

Scatter plots

Let’s map two measurement variables to the x and y axes, and then use hue to represent the grouping variable species.

<Figure size 640x480 with 1 Axes>

Here, we map body_mass_g to the point size with size.

<Figure size 640x480 with 1 Axes>

We move the legend to the side so we can see our data points better.

<Figure size 640x480 with 1 Axes>

Now let’s add island as shape with style.

<Figure size 640x480 with 1 Axes>

Looks like most of the Gentoos are on Biscoe and most of the Chinstraps are on Dream.

The Adelies are on all the islands.

This was seen in our original tabular visualization.

Loading...

Regression plots

Seaborn also include a regression plot in its collection of Axes level function.

Here we draw a line for the population as a whole.

<Figure size 640x480 with 1 Axes>

To show regression lines by species, we resort to creating subplots for individual groups.

<Figure size 800x600 with 1 Axes>

And here is one way to show both the group level and overall regression lines.

<Figure size 800x600 with 1 Axes>

Histograms

Of course, Seaborn does histograms.

<Figure size 640x480 with 1 Axes>
<Figure size 640x480 with 1 Axes>
<Figure size 640x480 with 1 Axes>

KDE plots

Seaborn also does KDE plots.

<Figure size 640x480 with 1 Axes>

KDE plots can plot two series on the x and y axes to produce this effect.

<Figure size 1000x1000 with 1 Axes>

Box plots

Seaborn does box plots, which are colored-in by default.

Passing the whole dataframe creates this plot, which is not very useful since the domains of each measure are different.

<Figure size 640x480 with 1 Axes>

Here is a single variable plotted.

Note the overly wide formatting by default.

<Figure size 640x480 with 1 Axes>

Adding a variable to hue creates a nice set of paired box plots.

This is actually hard to do in Pandas.

<Figure size 640x480 with 1 Axes>

Subplots

To create subplots with Seaborn’s Axes level function, you use Matplotlib’s subplot functions, e.g.

fig, ax = plt.subplots(2, 1, figsize=(5, 10))
<Figure size 1000x300 with 3 Axes>

Joint PLots

Seaborn offers some useful combination plots called Joint Plots.

These are not Axes level functions, however, and so can’t be manipulated by Matplotlib functions in the usual way.

<Figure size 600x600 with 3 Axes>
<Figure size 600x600 with 3 Axes>
<Figure size 600x600 with 3 Axes>