Data Science

A Major Seaborn Plotting Tip I Wish I Had Learned Earlier

Understanding Axes-level, Figure-level, and Object-level plots in Seaborn

Will Norris
February 2, 20217 min read

Hands-on Tutorials

From James Harrison (@jstrippa) on Unsplash
From James Harrison (@jstrippa) on Unsplash

Seaborn is a fantastic plotting library that I wish I had started using earlier in my Python carrier. I have always been a Matplotlib user and I would spend hours on some projects fine tuning the aesthetics of my plots so that they would really capture colleagues' attention during presentations. My first PI always said that if you don't show up to a meeting with plots you weren't prepared, so I always had something ready to go. Little did I know how simple Seaborn makes plotting in Python even while producing more visually appealing canned plots than Matplotlib.

The Data

We will be using a basic Seaborn data set about penguins with various recorded information about populations of several species. We can view the DataFrame below:

text
pen = sns.load_dataset('penguins')
text
pen.head()
Penguin Data Set
Penguin Data Set

Figure-level & Axes-level functions

Seaborn has a flat namespace to its code base. All of the functionality in Seaborn is accessed from the top level, however the code still has hierarchy to it. There are several modules with functions that may achieve the same goals but via different means.

When I first started working with Seaborn, I was confused why sometimes wrapping Matplotlib styling would work on altering my Seaborn plots, but other times the Matplotlib styling didn't work as expected. This is because some functions plot data onto a matplotlib.pyplot.Axes object, while other functions interface with Matplotlib through a Seaborn object. These are called axes-level and figure-level functions respectively.

In the hierarchy, axes-level functions sit underneath figure-level functions. For example, sns.displot() is a figure-level function that encompass thehistplot , kdeplot , ecdfplot , andrugplot axes-level functions. Each module in Seaborn has one figure-level function that can create any type of plot of the underlying axes-level functions. However, just because displot() can create all four kinds of plots, there are advantages and disadvantages to using the figure-level function or the more specific axes-level function.

Take a look at creating a simple KDE plot showing the kernel density of bill depth separated by species:

Figure Level

text
fig_lvl = sns.displot(data=pen, x='bill_depth_mm', hue='species', kind='kde', fill=True)
Figure-level KDE Plot
Figure-level KDE Plot
Figure Level Type
Figure Level Type

Axes Level

text
fig_ax = sns.kdeplot(data=pen, x='bill_depth_mm', hue='species', shade=True)
Axes-level KDE Plot
Axes-level KDE Plot
Axes Figure Type
Axes Figure Type

These two plots come out pretty similar looking. We can see that figure-level functions take the kind of plot as an argument. They also produce two different kinds of objects.

Also, notice how in order to shade them I used different keyword arguments. With sns.displot() I needed fill=True where sns.kdeplot() takes shade=True ; when using sns.kdeplot() , the keyword fill fills the curves with solid color instead of the more opaque shaded curves. Finding keyword arguments for sns.displot() can be difficult since it accommodates multiple kinds of plots.

Considerations

Styling

When we use an axes-level plot, we essentially are working with a fancy looking Matplotlib object. This leaves us a ton of further customization to be done with the Matplotlib functionality that many people are already accustomed to using.

Seaborn styling, on the other hand, can be more complex since multiple kinds of plots exist underneath each figure type. Because of this internal hierarchy, the docstrings for functions like sns.displot() won't contain all of the available arguments since some will only apply to certain kinds of plots. However, once you get used to the more difficult to find keywords for Seaborn figures they do work quite well and open up some very useful utilities.

Compatibility

When we create a Seaborn figure-level plot it is drawn on its own axis that is initiated when it is created. This means that we can't use a Seaborn figure-level plot on existing axes. However, Seaborn has some tricks up its sleeve to create grids of plots easily that we'll discuss below.

Axes-level plots are Matplotlib objects that can be treated like any other Matplotlib figure. They can be bundled into a grid of subplots made with Matplotlib, which can be really useful when you are making lots of different plots. Besides easier to follow documentation, Matplotlib compatibility is one of axes-level plots' greatest strengths.

Let's see how we can use Seaborn axes-level functions when we are working with Matplotlib subplots:

text
fig, ax = plt.subplots(1,2,figsize=(8,4), gridspec_kw=dict(width_ratios=[4,3]))
text
sns.scatterplot(data=pen, x='bill_depth_mm',y='body_mass_g', hue='species', ax=ax[0])
text
sns.kdeplot(data=pen, x='bill_depth_mm', hue='species', shade=True, ax=ax[1])
text
fig.tight_layout()
Seaborn Axes-level figures in Matplotlib Subplots
Seaborn Axes-level figures in Matplotlib Subplots

Changing Figure Size and Labeling Axes

The first two things I often do to a new plot is make it uniform in size with my other plots and label the axes. With Matplotlib sizing plots and labeling axes are familiar tasks to many, and while Seaborn is different it's still quite simple.

Axes-level

Axes-level plots use the standard Matplotlib figure instantiation to determine size and Matplotlib commands to set each axis label.

text
plt.figure(figsize=(12,6))
text
fig_ax = sns.histplot(data=pen, x='bill_depth_mm', hue='species', multiple='stack')
text
plt.xlabel('Bill Depth (mm)')
Set Labels & Size with Axes-label Plot
Set Labels & Size with Axes-label Plot

Figure-level

Figure-level plots use height and aspect parameters when creating the figure and Seaborn's own axis label function.

text
fig_lvl = sns.displot(data=pen, x='bill_depth_mm', hue='species', multiple='stack', kind='hist', height=5, aspect=2)
text
fig_lvl.set_axis_labels("Bill Depth (mm)")
Set Labels & Size with Figure-level Plot
Set Labels & Size with Figure-level Plot

Subplots with Seaborn Figure-level Plots

We can use Seaborn to create some pretty useful plot grids by automatically separating dating by a categorical variable. Doing this with Matplolib can be much more work with subsetting data and creating the individual plots for each axis.

text
fig_lvl = sns.relplot(data=pen, x='bill_depth_mm', y='body_mass_g', col='species', kind='scatter')
text
fig_lvl.set_axis_labels("Bill Depth (mm)", "Body Mass (g)")
Figure-level Scatter Plot Easily Divided By a Categorical Variable
Figure-level Scatter Plot Easily Divided By a Categorical Variable

Using Matplotlib with Subplots

This kind of plot can also be made with Matplotlib but it requires more thought. Here is how I made it:

text
species = pen['species'].unique()fig, ax = plt.subplots(1,3,figsize=(16,6))
text
for a, spec_name in zip(ax,species):     df = pen[pen['species'].str.match(spec_name)]    a.scatter(x=df['bill_depth_mm'], y=df['body_mass_g'],s=15)    a.set_xlim([10,23])    a.set_ylim([2000,6500])    a.set_title(spec_name)
Subplots with Matplotlib
Subplots with Matplotlib

I chose to use a for loop to step through each axis and each species name. This way you can do things like set your x and y boundaries without repeating the same code for each axis. This is more work and took more consideration than Seaborn. I have to manually subset by the species, make the correct number of subplots, and set reasonable x/y limits with respect to all of the data; Seaborn does all of this automatically! Pretty nice.

Object-level Plots

When you use the figure-level function, sns.displot() , to create a histogram the object type was seaborn.axisgrid.FacetGrid meaning it is a Seaborn FacetGrid object that interfaces with the Matplotlib API to be displayed. We can also create a plot using the object directly, which opens up further customization.

text
fig_obj = sns.FacetGrid(pen, col='species', margin_titles=True, height=6)
text
fig_obj.map(plt.scatter, "bill_depth_mm", "body_mass_g", s=30)
text
fig_obj.set(xlim=(10,23),ylim=(2000,6500))
text
fig_obj.set_axis_labels("Bill Depth (mm)", "Body Mass (g)", fontsize=14)
Object-level Plot
Object-level Plot

This scatter plot looks identical to our Figure-level sns.relplot() plot but leverages plt.scatter through the Seaborn FacetGrid object. This is a much easier way to achieve this kind of plot using Matplotlib. To adjust your plot further using Matplotlib syntax, you can either add more keyword arguments to the map() call or use the fig_obj.set() function. You can also use the functions for Seaborn figure-level plots like fig.et_axis_labels() .

Objects Give Flexibility

There is a lot more that we can do with Seaborn objects. They are more difficult to use; often you may have to open two (or more) pages of documentation to get all of the parameters you are looking for. But that extra work is rewarded with some great strengths like easy faceting by data variables.

text
fig = sns.FacetGrid(pen, col="island", hue="species", aspect=.75, height=3.5)
text
fig.map_dataframe(sns.scatterplot, x="bill_depth_mm", y="body_mass_g")
text
fig.set_axis_labels("Bill Depths (mm)", "Body Mass (g)")
text
fig.add_legend()
Seaborn FacetGrid Plot using sns.scatterplot
Seaborn FacetGrid Plot using sns.scatterplot

Wrapping Up

It will save you time to understand the hierarchy of functions that exist within Seaborn. The majority of the time an axes-level function is going to be the most straightforward option. The documentation is easier to find and follow, and if you decide to include them with other Matplotlib plots they are compatible.

As we can see by using relplot() to split a plot by a categorical variable above, Seaborn figures make some visualizations much simpler to create than Matplotlib. So, while the majority of basic plots can be created as a Matplolib axes Object there are good use cases for using a Seaborn Figure Object instead. Seaborn may be designed to offer the user simplicity but it has advanced functionality to aid in perfecting your plotting goals in Python.

Documentation

Disclaimer: All plots in this article were made by me for this purpose.

Related Articles