Lecture 11
Seaborn is a library for making statistical graphics in Python. It builds on top of matplotlib and integrates closely with pandas data structures.
Seaborn helps you explore and understand your data. Its plotting functions operate on dataframes and arrays containing whole datasets and internally perform the necessary semantic mapping and statistical aggregation to produce informative plots. Its dataset-oriented, declarative API lets you focus on what the different elements of your plots mean, rather than on the details of how to draw them.
species island bill_length_mm ... flipper_length_mm body_mass_g sex
0 Adelie Torgersen 39.1 ... 181.0 3750.0 Male
1 Adelie Torgersen 39.5 ... 186.0 3800.0 Female
2 Adelie Torgersen 40.3 ... 195.0 3250.0 Female
3 Adelie Torgersen NaN ... NaN NaN NaN
4 Adelie Torgersen 36.7 ... 193.0 3450.0 Female
.. ... ... ... ... ... ... ...
339 Gentoo Biscoe NaN ... NaN NaN NaN
340 Gentoo Biscoe 46.8 ... 215.0 4850.0 Female
341 Gentoo Biscoe 50.4 ... 222.0 5750.0 Male
342 Gentoo Biscoe 45.2 ... 212.0 5200.0 Female
343 Gentoo Biscoe 49.9 ... 213.0 5400.0 Male
[344 rows x 7 columns]
To adjust the size of plots generated via a figure-level plotting function adjust the aspect
and height
arguments, figure width is aspect * height
.
Figure-level plotting methods return a FacetGrid
object (which is a wrapper around lower level pyplot figure(s) and axes).
Method | Description |
---|---|
add_legend() |
Draw a legend, maybe placing it outside axes and resizing the figure |
despine() |
Remove axis spines from the facets. |
facet_axis() |
Make the axis identified by these indices active and return it. |
facet_data() |
Generator for name indices and data subsets for each facet. |
map() |
Apply a plotting function to each facet’s subset of the data. |
map_dataframe() |
Like .map() but passes args as strings and inserts data in kwargs. |
refline() |
Add a reference line(s) to each facet. |
savefig() |
Save an image of the plot. |
set() |
Set attributes on each subplot Axes. |
set_axis_labels() |
Set axis labels on the left column and bottom row of the grid. |
set_titles() |
Draw titles either above each facet or on the grid margins. |
set_xlabels() |
Label the x axis on the bottom row of the grid. |
set_xticklabels() |
Set x axis tick labels of the grid. |
set_ylabels() |
Label the y axis on the left column of the grid. |
set_yticklabels() |
Set y axis tick labels on the left column of the grid. |
tight_layout() |
Call fig.tight_layout within rect that exclude the legend. |
Attribute | Description |
---|---|
ax |
The matplotlib.axes.Axes when no faceting variables are assigned. |
axes |
An array of the matplotlib.axes.Axes objects in the grid. |
axes_dict |
A mapping of facet names to corresponding matplotlib.axes.Axes . |
figure |
Access the matplotlib.figure.Figure object underlying the grid. |
legend |
The matplotlib.legend.Legend object, if present. |
There is one last figure-level plot type - lmplot()
which is a convenient interface to fitting and ploting regression models across subsets of data,
These functions return a matplotlib.pyplot.Axes
object instead of a FacetGrid
giving more direct control over the plot using basic matplotlib tools.
fig, axs = plt.subplots(
2, 1, figsize=(4,6),
layout = "constrained",
sharex=True
)
sns.scatterplot(
data = penguins,
x = "bill_length_mm", y = "bill_depth_mm",
hue = "species",
ax = axs[0]
)
axs[0].get_legend().remove()
sns.kdeplot(
data = penguins,
x = "bill_length_mm", hue = "species",
fill=True, alpha=0.5,
ax = axs[1]
)
plt.show()
plt.figure(figsize=(5,5),
layout = "constrained")
sns.kdeplot(
data = penguins,
x = "bill_length_mm", y = "bill_depth_mm",
hue = "species"
)
sns.scatterplot(
data = penguins,
x = "bill_length_mm", y = "bill_depth_mm",
hue = "species", alpha=0.5
)
sns.rugplot(
data = penguins,
x = "bill_length_mm", y = "bill_depth_mm",
hue = "species"
)
plt.legend()
plt.show()
Seaborn comes with a number of themes (darkgrid
, whitegrid
, dark
, white
, and ticks
) which can be enabled at the figure level with sns.set_theme()
or at the axes level with sns.axes_style()
.
All of the examples below are the result of calls to sns.color_palette()
with as_cmap=True
for the continuous case,
Palettes are applied via the set_palette()
function,
pairplot()
is a special case of the more general PairGrid
- once constructed there are methods that allow for mapping plot functions of the different axes,
x_vars = ["body_mass_g", "bill_length_mm", "bill_depth_mm", "flipper_length_mm"]
y_vars = ["body_mass_g"]
( sns.PairGrid(
penguins, hue = "species", x_vars=x_vars, y_vars=y_vars, height=3
)
.map_diag(
sns.kdeplot, fill=True
)
.map_offdiag(
sns.scatterplot, size=penguins["body_mass_g"]
)
.add_legend()
)
Just like PairGrid
s it is possible to construct FacetGrid
s from scratch,
One final figure-level plot, is a joint plot which includes marginal distributions along the x and y-axis.
The main plot (joint) and the margins (marginal) can be modified by keywords or via layering (use plot_joint()
and plot_marginals()
methods).
Sta 663 - Spring 2023