Skip to main content
v2026.11,986 entries · CC-BY 4.0

seaborn FacetGrid: Syntax, map vs map_dataframe and Examples

How to build faceted plots with seaborn FacetGrid: syntax, map vs map_dataframe, a decision table against relplot and catplot, and troubleshooting.

Written and maintained by CASRAI Editorial Board

Published

On this page

seaborn.FacetGrid is the seaborn class that draws a multi-plot grid for conditional relationships: you split one tidy (long-form) pandas DataFrame by up to three variables (row, col and hue) and draw the same plot type in every panel. You create the grid with sns.FacetGrid(data, col=...), which draws nothing yet, and then draw into it with g.map() or g.map_dataframe(). This page uses the seaborn 0.13.2 documentation and its built-in tips dataset for every example.

What FacetGrid is used for in research

Research data is rarely one distribution or one relationship. A typical dataset has a treatment or condition, a site or batch, and a measured outcome, and the question is whether the pattern in the outcome holds within each subgroup. The seaborn documentation describes FacetGrid as a tool for exactly this: “conditional relationships”. One panel per level of a variable lets a reader compare subgroups at a glance, with the same axes and the same plot type in every panel.

The grid can be drawn with up to three dimensions: row, col and hue. Rows and columns split the figure into panels; hue splits the data inside each panel by colour. FacetGrid also exposes the underlying Matplotlib Figure and Axes, so anything Matplotlib can do to a figure you can still do to the grid.

One point from the official tutorial shapes how you should use the class. Four seaborn functions, relplot, displot, catplot and lmplot, use FacetGrid internally and return it. The documentation says they take care of important bookkeeping that synchronizes the multiple plots in each grid, and recommends them for most cases. Direct use of FacetGrid is for the cases those functions cannot express, which is covered in the decision table below.

Install or access

FacetGrid ships inside seaborn; there is nothing separate to install. The official installation page gives these routes:

  • pip install seaborn
  • pip install seaborn[stats] (adds the optional statistical dependencies)
  • conda install seaborn, or conda install seaborn -c conda-forge

The installation page states that seaborn requires Python 3.8 or newer and lists NumPy, pandas and Matplotlib as mandatory dependencies. Check the installation page for the requirements of the release you install, since they change between versions. Import it as import seaborn as sns and import matplotlib.pyplot as plt; the examples below load the tips dataset with sns.load_dataset("tips").

Step-by-step: build a faceted figure

Step 1: get the data into long form

FacetGrid expects a tidy, long-form DataFrame: each variable is a column and each observation is a row. The seaborn data-structure tutorial advises using long-form structure when possible for serious analysis. If your measurements sit in one column per condition (a common layout for repeated measures or replicates), reshape them with melt first. The tutorial’s own example does this:

anagrams_long = anagrams.melt(id_vars=["subidr", "attnr"], var_name="solutions", value_name="score")

After the melt, solutions is a single column you can facet on and score is a single column you can plot. Faceting a wide table directly is the most common reason a grid comes out wrong.

Step 2: create the grid

import seaborn as sns
import matplotlib.pyplot as plt

tips = sns.load_dataset("tips")
g = sns.FacetGrid(tips, col="time", row="sex")

This draws empty panels only: one column per level of time and one row per level of sex. Nothing is plotted until you call a mapping method.

Step 3: draw with map

g.map(sns.scatterplot, "total_bill", "tip")

map(func, *args, **kwargs) calls the plotting function once per panel, passing the named columns as positional arguments. This is the simple route for functions that take the variables positionally, such as Matplotlib-style functions.

Step 4: draw with map_dataframe for keyword-style seaborn functions

g = sns.FacetGrid(tips, col="time")
g.map_dataframe(sns.histplot, x="total_bill", binwidth=2, binrange=(0, 60))

map_dataframe(func, *args, **kwargs) is for functions that accept a data argument and named variables. Column names are given as strings and the panel’s data is inserted into the keyword arguments for you. The table below sets the two methods side by side.

Question map map_dataframe
Signature map(func, *args, **kwargs) map_dataframe(func, *args, **kwargs)
Example from the docs g.map(sns.scatterplot, "total_bill", "tip") g.map_dataframe(sns.histplot, x="total_bill", binwidth=2, binrange=(0, 60))
Typical function Takes the variables as positional arguments Takes data plus named variables, as most seaborn functions do
Hue and legend Pass hue to FacetGrid, map the function, then call g.add_legend()

Step 5: add hue, wrap, reference lines and annotations

Each of the following patterns comes from the seaborn reference page.

  • Hue inside panels: g = sns.FacetGrid(tips, col="time", hue="sex"), then g.map_dataframe(sns.scatterplot, x="total_bill", y="tip") and g.add_legend().
  • Wrap one variable with many levels: sns.FacetGrid(tips, col="size", height=2.5, col_wrap=3).
  • Reference line: g.refline(y=tips["tip"].median()) draws the same horizontal line in every panel.
  • Sample size per panel: write a small function that draws on the current Axes and call it with g.map_dataframe.
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(annotate)

Printing N in each panel is worth doing for research figures, because subgroup sizes are what a reader needs to judge how much weight each panel deserves.

Step 6: label, set limits and save

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")

Use set_axis_labels to replace column names with labels that carry units, set_titles to control panel titles with templates, set to pass any Matplotlib Axes property to every panel, and savefig to write the figure. To work on panels individually, loop over g.axes_dict.items(), whose keys are (row_val, col_val) pairs.

FacetGrid or a figure-level function?

The official tutorial’s recommendation is to prefer the figure-level functions, and the reference page warns that when seaborn functions infer semantic mappings, care is needed to synchronize the mappings across facets. The table sums up the choice.

Use When it fits Source statement
relplot Faceted scatter or line plots Uses FacetGrid internally and returns it; synchronizes the plots in the grid
displot Faceted distributions Uses FacetGrid internally and returns it
catplot Faceted categorical plots Uses FacetGrid internally and returns it
lmplot Faceted regression fits Uses FacetGrid internally and returns it
FacetGrid directly A custom plotting function, or a function without a figure-level wrapper Custom functions must draw on the active Axes, accept data as positional arguments, and handle color and label keyword arguments

Related guides on this site cover the single-panel versions of these plots: seaborn histograms, seaborn line plots, seaborn pairplot and strip plots. For the library itself see seaborn vs Matplotlib.

Output and how to read it

The output is a FacetGrid object. Its figure attribute is the Matplotlib Figure (the older fig attribute is deprecated), axes is an array of the panels, axes_dict maps (row, col) values to Axes, and legend holds the legend if you added one. To read a faceted figure in a research setting:

  • Check that axis limits are shared. sharex and sharey default to True, which keeps panels comparable; they also accept 'col' and 'row'.
  • Check the panel titles against the levels of your variable before drawing conclusions about a subgroup.
  • Compare the N in each panel (Step 5) before comparing shapes.
  • Record the seaborn and Matplotlib versions with the figure, so the result can be regenerated. See computational reproducibility.

Troubleshooting

  • Error combining col_wrap and row. col_wrap cannot be used together with row. Facet one variable with col_wrap, or use row and col without it. gridspec_kws is also ignored when col_wrap is set.
  • Colours or categories differ between panels. Mappings inferred by seaborn functions are not automatically synchronized across facets. Use a figure-level function such as relplot or catplot, or set hue_order, row_order, col_order and palette explicitly.
  • Empty panels or missing categories. dropna defaults to False, so rows with missing values in the faceting variables are not dropped for you. Check the data first.
  • Margin titles do not appear. margin_titles is marked experimental, and the tutorial notes it is not formally supported by the Matplotlib API and may not work in all cases.
  • Nothing is drawn. Creating the grid draws nothing. Call map or map_dataframe.
  • Your function draws on the wrong panel. A custom function must draw on the active Axes (use plt.gca()), accept data as positional arguments, and handle color and label keyword arguments.
  • Deprecation warning for g.fig. Use g.figure.

The full parameter list, with defaults, is in the data table below this page.

Alternatives

All four figure-level functions are part of seaborn and, like Matplotlib and pandas, are free open-source Python libraries. The section above lists which of them to use in place of a direct FacetGrid call.

Frequently asked questions

What does FacetGrid do in seaborn?

It builds a multi-plot grid for conditional relationships, splitting a long-form DataFrame by row, col and hue and drawing the same plot in each panel.

What is the difference between map and map_dataframe?

map passes the named columns to the plotting function as positional arguments. map_dataframe passes the panel’s data and the variables as keyword arguments, which suits seaborn functions that take x=, y= and data.

How many variables can a FacetGrid use?

Up to three: row, col and hue.

Should I use FacetGrid or relplot, displot, catplot and lmplot?

The seaborn documentation recommends the figure-level functions for most cases, because they synchronize the plots in the grid. Use FacetGrid when you need a custom function.

How do I save a FacetGrid?

Call g.savefig("facet_plot.png"), or use the Matplotlib Figure through g.figure.

Why can I not use col_wrap with row?

The documentation states that col_wrap cannot be combined with row.

Sources

Data: seaborn FacetGrid constructor parameters and defaults (seaborn 0.13.2)

Constructor parameters of seaborn.FacetGrid with their default values and documented behaviour, compiled from the seaborn 0.13.2 reference page and the multi-plot grids tutorial.

seaborn FacetGrid constructor parameters and defaults (seaborn 0.13.2)
ParameterDefaultDocumented behaviour
data—Tidy long-form DataFrame to plot
row, col, hueNoneVariables that split the data into rows of panels, columns of panels and colours (up to three dimensions)
col_wrapNoneWraps the column variable at this width; cannot be combined with row; gridspec_kws ignored when set
sharex, shareyTrueShare axes across panels; bool, 'col' or 'row'
height, aspect3, 1Facet height in inches; width is aspect × height
paletteNoneColours for the hue variable
row_order, col_order, hue_orderNoneOrder of the levels in each dimension
hue_kwsNoneExtra keyword arguments varied by hue level
dropnaFalseWhether to drop rows with missing values in the faceting variables
legend_outTruePlaces the legend outside the grid, centre right
despineTrueRemoves the top and right spines
margin_titlesFalsePuts row titles in the right margin; marked experimental
xlim, ylimNoneAxis limits for each facet
subplot_kws, gridspec_kwsNoneKeyword arguments passed to Matplotlib subplot creation and the GridSpec

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about seaborn FacetGrid: Syntax, map vs map_dataframe and Examples

2 free questions a day, no account.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →