seaborn.
FacetGrid
(**kwargs)¶Multi-plot grid for plotting conditional relationships.
__init__
(self, data, *, row=None, col=None, hue=None, col_wrap=None, sharex=True, sharey=True, height=3, aspect=1, palette=None, row_order=None, col_order=None, hue_order=None, hue_kws=None, dropna=False, legend_out=True, despine=True, margin_titles=False, xlim=None, ylim=None, subplot_kws=None, gridspec_kws=None, size=None)¶Initialize the matplotlib figure and FacetGrid object.
This class maps a dataset onto multiple axes arrayed in a grid of rows and columns that correspond to levels of variables in the dataset. The plots it produces are often called “lattice”, “trellis”, or “small-multiple” graphics.
It can also represent levels of a third variable with the hue
parameter, which plots different subsets of data in different colors.
This uses color to resolve elements on a third dimension, but only
draws subsets on top of each other and will not tailor the hue
parameter for the specific visualization the way that axes-level
functions that accept hue
will.
The basic workflow is to initialize the FacetGrid
object with
the dataset and the variables that are used to structure the grid. Then
one or more plotting functions can be applied to each subset by calling
FacetGrid.map()
or FacetGrid.map_dataframe()
. Finally, the
plot can be tweaked with other methods to do things like change the
axis labels, use different ticks, or add a legend. See the detailed
code examples below for more information.
Warning
When using seaborn functions that infer semantic mappings from a
dataset, care must be taken to synchronize those mappings across
facets (e.g., by defing the hue
mapping with a palette dict or
setting the data type of the variables to category
). In most cases,
it will be better to use a figure-level function (e.g. relplot()
or catplot()
) than to use FacetGrid
directly.
See the tutorial for more information.
Tidy (“long-form”) dataframe where each column is a variable and each row is an observation.
Variables that define subsets of the data, which will be drawn on
separate facets in the grid. See the {var}_order
parameters to
control the order of levels of this variable.
“Wrap” the column variable at this width, so that the column facets
span multiple rows. Incompatible with a row
facet.
If true, the facets will share y axes across columns and/or x axes across rows.
Height (in inches) of each facet. See also: aspect
.
Aspect ratio of each facet, so that aspect * height
gives the width
of each facet in inches.
Colors to use for the different levels of the hue
variable. Should
be something that can be interpreted by color_palette()
, or a
dictionary mapping hue levels to matplotlib colors.
Order for the levels of the faceting variables. By default, this
will be the order that the levels appear in data
or, if the
variables are pandas categoricals, the category order.
Other keyword arguments to insert into the plotting call to let other plot attributes vary across levels of the hue variable (e.g. the markers in a scatterplot).
If True
, the figure size will be extended, and the legend will be
drawn outside the plot on the center right.
Remove the top and right spines from the plots.
If True
, the titles for the row variable are drawn to the right of
the last column. This option is experimental and may not work in all
cases.
Limits for each of the axes on each facet (only relevant when share{x, y} is True).
Dictionary of keyword arguments passed to matplotlib subplot(s) methods.
Dictionary of keyword arguments passed to
matplotlib.gridspec.GridSpec
(via matplotlib.figure.Figure.subplots()
).
Ignored if col_wrap
is not None
.
See also
Examples
Note
These examples use seaborn functions to demonstrate some of the
advanced features of the class, but in most cases you will want
to use figue-level functions (e.g. displot()
, relplot()
)
to make the plots shown here.
Calling the constructor requires a long-form data object. This initializes the grid, but doesn’t plot anything on it:
tips = sns.load_dataset("tips")
sns.FacetGrid(tips)
Assign column and/or row variables to add more subplots to the figure:
sns.FacetGrid(tips, col="time", row="sex")
To draw a plot on every facet, pass a function and the name of one or more columns in the dataframe to FacetGrid.map()
:
g = sns.FacetGrid(tips, col="time", row="sex")
g.map(sns.scatterplot, "total_bill", "tip")
The variable specification in FacetGrid.map()
requires a positional argument mapping, but if the function has a data
parameter and accepts named variable assignments, you can also use FacetGrid.map_dataframe()
:
g = sns.FacetGrid(tips, col="time", row="sex")
g.map_dataframe(sns.histplot, x="total_bill")
Notice how the bins have different widths in each facet. A separate plot is drawn on each facet, so if the plotting function derives any parameters from the data, they may not be shared across facets. You can pass additional keyword arguments to synchronize them. But when possible, using a figure-level function like displot()
will take care of this bookkeeping for you:
g = sns.FacetGrid(tips, col="time", row="sex")
g.map_dataframe(sns.histplot, x="total_bill", binwidth=2, binrange=(0, 60))
The FacetGrid
constructor accepts a hue
parameter. Setting this will condition the data on another variable and make multiple plots in different colors. Where possible, label information is tracked so that a single legend can be drawn:
g = sns.FacetGrid(tips, col="time", hue="sex")
g.map_dataframe(sns.scatterplot, x="total_bill", y="tip")
g.add_legend()
When hue
is set on the FacetGrid
, however, a separate plot is drawn for each level of the variable. If the plotting function understands hue
, it is better to let it handle that logic. But it is important to ensure that each facet will use the same hue mapping. In the sample tips
data, the sex
column has a categorical datatype, which ensures this. Otherwise, you may want to use the hue_order
or similar parameter:
g = sns.FacetGrid(tips, col="time")
g.map_dataframe(sns.scatterplot, x="total_bill", y="tip", hue="sex")
g.add_legend()
The size and shape of the plot is specified at the level of each subplot using the height
and aspect
parameters:
g = sns.FacetGrid(tips, col="day", height=3.5, aspect=.65)
g.map(sns.histplot, "total_bill")
If the variable assigned to col
has many levels, it is possible to “wrap” it so that it spans multiple rows:
g = sns.FacetGrid(tips, col="size", height=2.5, col_wrap=3)
g.map(sns.histplot, "total_bill")
To add horizontal or vertical reference lines on every facet, use FacetGrid.refline()
:
g = sns.FacetGrid(tips, col="time", margin_titles=True)
g.map_dataframe(sns.scatterplot, x="total_bill", y="tip")
g.refline(y=tips["tip"].median())
You can pass custom functions to plot with, or to annotate each facet. Your custom function must use the matplotlib state-machine interface to plot on the “current” axes, and it should catch additional keyword arguments:
import matplotlib.pyplot as plt
def annotate(data, **kws):
n = len(data)
ax = plt.gca()
ax.text(.1, .6, f"N = {n}", transform=ax.transAxes)
g = sns.FacetGrid(tips, col="time")
g.map_dataframe(sns.scatterplot, x="total_bill", y="tip")
g.map_dataframe(annotate)
The FacetGrid
object has some other useful parameters and methods for tweaking the plot:
g = sns.FacetGrid(tips, col="sex", row="time", margin_titles=True)
g.map_dataframe(sns.scatterplot, x="total_bill", y="tip")
g.set_axis_labels("Total bill ($)", "Tip ($)")
g.set_titles(col_template="{col_name} patrons", row_template="{row_name}")
g.set(xlim=(0, 60), ylim=(0, 12), xticks=[10, 30, 50], yticks=[2, 6, 10])
g.tight_layout()
g.savefig("facet_plot.png")
You also have access to the underlying matplotlib objects for additional tweaking:
g = sns.FacetGrid(tips, col="sex", row="time", margin_titles=True, despine=False)
g.map_dataframe(sns.scatterplot, x="total_bill", y="tip")
g.figure.subplots_adjust(wspace=0, hspace=0)
for (row_val, col_val), ax in g.axes_dict.items():
if row_val == "Lunch" and col_val == "Female":
ax.set_facecolor(".95")
else:
ax.set_facecolor((0, 0, 0, 0))
Methods
|
Initialize the matplotlib figure and FacetGrid object. |
|
Draw a legend, maybe placing it outside axes and resizing the figure. |
|
Remove axis spines from the facets. |
|
Make the axis identified by these indices active and return it. |
|
Generator for name indices and data subsets for each facet. |
|
Apply a plotting function to each facet’s subset of the data. |
|
Like |
|
Add a reference line(s) to each facet. |
|
Save an image of the plot. |
|
Set attributes on each subplot Axes. |
|
Set axis labels on the left column and bottom row of the grid. |
|
Draw titles either above each facet or on the grid margins. |
|
Label the x axis on the bottom row of the grid. |
|
Set x axis tick labels of the grid. |
|
Label the y axis on the left column of the grid. |
|
Set y axis tick labels on the left column of the grid. |
|
Call fig.tight_layout within rect that exclude the legend. |
Attributes
|
The |
|
An array of the |
|
A mapping of facet names to corresponding |
|
DEPRECATED: prefer the |
|
Access the |
|
The |