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(), andsns.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 Type | Pandas | Seaborn Axes | Seaborn Figure | Seaborn Object |
|---|---|---|---|---|
| Scatter Plot | df.plot.scatter() | sns.scatterplot() | sns.relplot(kind="scatter") | so.Plot().add(so.Dot()) |
| Line Plot | df.plot.line() | sns.lineplot() | sns.relplot(kind="line") | so.Plot().add(so.Line()) |
| Histogram | df.plot.hist() | sns.histplot() | sns.displot(kind="hist") | so.Plot().add(so.Bar(), so.Hist()) |
| KDE Plot | df.plot.kde() | sns.kdeplot() | sns.displot(kind="kde") | so.Plot().add(so.Line(), so.KDE()) |
| Box Plot | df.plot.box() | sns.boxplot() | sns.catplot(kind="box") | so.Plot().add(so.Box()) |
| Bar Plot | df.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.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
penguins = sns.load_dataset('penguins').dropna()
penguins.head()To create a bar plot showing the counts of a category variable, we can first compute the value_counts and then plot them directly.
penguins.species.value_counts()species
Adelie 146
Gentoo 119
Chinstrap 68
Name: count, dtype: int64sns.barplot(penguins.species.value_counts())
plt.show()
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.
sns.countplot(penguins, x='species')
plt.show()
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:
my_order = penguins['species'].value_counts().index
sns.countplot(penguins, x='species', order=my_order)
plt.show()
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.
sns.barplot(penguins, x='species', y='bill_depth_mm')
plt.show()
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.
sns.barplot(penguins, x='species', y='bill_depth_mm', estimator='sum')
plt.show()
If you don’t want to have the error calculated and show the bars, set errorbar=None.
sns.barplot(penguins, x='species', y='bill_depth_mm', errorbar=None)
plt.show()
Two grouping variables
To show a second grouping variable, just set hue to that variable.
Seaborn handles the data transformation for you.
sns.barplot(penguins, x='species', y='bill_depth_mm', hue='sex')
plt.show()
You can use hue on count plots, too.
sns.countplot(penguins, x='species', hue='sex')
plt.show()
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.
dowjones = sns.load_dataset('dowjones')
dowjones.head()sns.lineplot(dowjones, x='Date', y='Price')
plt.show()
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.
dowjones1 = dowjones.set_index('Date')
sns.lineplot(dowjones1)
plt.show()
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.
fig, ax = plt.subplots(figsize=(10, 6))
sns.lineplot(dowjones, x='Date', y='Price', ax=ax)
plt.show()
Using a grouping variable
Let’s look at an example where there is a grouping variable.
flights = sns.load_dataset('flights')
flights.head()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.
sns.lineplot(flights, x='year', y='passengers')
plt.show()
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.
sns.lineplot(flights, x='year', y='passengers', errorbar='sd')
plt.show()
Or, to lose the representation of error altogether, do this:
sns.lineplot(flights, x='year', y='passengers', errorbar=None)
plt.show()
To bypass aggregation and actually show lines for each value of the grouping variable month, we set hue to that variable.
sns.lineplot(flights, x='year', y='passengers', hue='month')
plt.show()
A more interesting plot in this case would be to set the hue to year and x to month.
sns.lineplot(flights, x='month', y='passengers', hue='year')
plt.show()
Notice that although Seaborn expects tidy data, you can also pass it a wide dataframe and it will (usually) know what to do.
flights_wide = flights.pivot(index='month', columns='year', values='passengers')
flights_wide.head()sns.lineplot(flights_wide)
plt.show()
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.
healthexp = sns.load_dataset('healthexp')
ax = sns.lineplot(data=healthexp, x='Year', y='Spending_USD', errorbar=None)
# You have to use Matplotlib to grab the line first
line = ax.lines[0]
x = line.get_xdata()
y = line.get_ydata()
ax.fill_between(x, y, color=line.get_color(), alpha=0.3)
# ax.fill_between(x, y, 0, color=line.get_color(), alpha=0.3) # Same
ax.set_xlim(1970, 2020)
ax.set_ylim(0, None)
plt.show()
Scatter plots¶
Let’s map two measurement variables to the x and y axes, and then use hue to represent the grouping variable species.
sns.scatterplot(penguins, x='bill_length_mm', y='bill_depth_mm', hue='species')
plt.suptitle("Seaborn Test", y=.95)
plt.show()
Here, we map body_mass_g to the point size with size.
sns.scatterplot(penguins,
x='bill_length_mm',
y='bill_depth_mm',
hue='species',
size='body_mass_g')
plt.suptitle("Seaborn Test")
plt.show()
We move the legend to the side so we can see our data points better.
sns.scatterplot(penguins,
x='bill_length_mm',
y='bill_depth_mm',
hue='species',
size='body_mass_g'
)
plt.legend(loc='center left', bbox_to_anchor=(1, .5))
plt.show()
Now let’s add island as shape with style.
sns.scatterplot(penguins,
x='bill_length_mm',
y='bill_depth_mm',
hue='species',
size='body_mass_g',
style='island'
)
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.show()
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.
penguins.value_counts(['species', 'island']).unstack(fill_value=0).style.background_gradient(cmap='Blues', axis=None)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.
sns.regplot(penguins, x='bill_length_mm', y='bill_depth_mm')
plt.show()
To show regression lines by species, we resort to creating subplots for individual groups.
fig, ax = plt.subplots(figsize=(8, 6))
for species, subset in penguins.groupby('species'):
sns.regplot(subset, x="bill_length_mm", y="bill_depth_mm", ax=ax, label=species)
ax.set_xlabel("Bill Length (mm)")
ax.set_ylabel("Bill Depth (mm)")
ax.legend(title="Species")
plt.show()
And here is one way to show both the group level and overall regression lines.
fig, ax = plt.subplots(figsize=(8, 6))
sns.regplot(penguins, x='bill_length_mm', y='bill_depth_mm', ax=ax, color='gray')
for species, subset in penguins.groupby('species'):
sns.regplot(subset, x="bill_length_mm", y="bill_depth_mm", ax=ax, label=species)
ax.set_xlabel("Bill Length (mm)")
ax.set_ylabel("Bill Depth (mm)")
ax.legend(title="Species")
plt.show()
Histograms¶
Of course, Seaborn does histograms.
sns.histplot(penguins, x='bill_length_mm')
plt.show()
sns.histplot(penguins, x='bill_length_mm', hue='species')
plt.show()
sns.histplot(penguins, x='body_mass_g', hue='sex', bins=30)
plt.show()
KDE plots¶
Seaborn also does KDE plots.
sns.kdeplot(penguins, x='body_mass_g', hue='species', fill=True)
plt.show()
KDE plots can plot two series on the x and y axes to produce this effect.
fig, ax = plt.subplots(figsize=(10,10))
sns.kdeplot(penguins, x='bill_length_mm', y='bill_depth_mm', hue='species', fill=True, ax=ax)
plt.show()
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.
sns.boxplot(penguins)
plt.show()
Here is a single variable plotted.
Note the overly wide formatting by default.
sns.boxplot(penguins, x='bill_length_mm')
plt.show()
Adding a variable to hue creates a nice set of paired box plots.
This is actually hard to do in Pandas.
sns.boxplot(penguins, x='species', y='bill_depth_mm', hue='sex')
plt.show()
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))fig, ax = plt.subplots(1, 3, figsize=(10, 3), sharey=True, sharex=True)
for i, group in enumerate(penguins.groupby('species')):
species, subset = group
sns.histplot(subset, x='body_mass_g', ax=ax[i], stat='density', color='tab:gray')
sns.kdeplot(subset, x='body_mass_g', ax=ax[i])
ax[i].set_title(species)
plt.show()
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.
sns.jointplot(data=penguins, x="bill_length_mm", y="bill_depth_mm", hue='species', kind="scatter")
plt.suptitle("Joint Plot")
plt.show()
sns.jointplot(data=penguins, x="bill_length_mm", y="bill_depth_mm", hue='species', kind="kde", fill=True)
plt.suptitle("Joint Plot")
plt.show()
sns.jointplot(data=penguins, x="bill_length_mm", y="bill_depth_mm", hue='species', kind="hist", bins=20)
plt.suptitle("Joint Plot", y=1.01)
plt.show()