Using Seaborn FacetGrid for Multi‑Plot Visualizations in Python
This guide explains how to leverage Seaborn's FacetGrid to create multiple coordinated plots, covering basic usage, parameter options, and customization techniques such as adding legends, titles, axis labels, figure size, and DPI settings, with complete Python code examples.
Seaborn is a Python visualization library built on Matplotlib that provides a high‑level interface and predefined styles, allowing many plots to be created with a single line of code. Compared with raw Matplotlib, Seaborn produces more attractive and concise graphics.
FacetGrid enables the construction of multiple sub‑plots in a single figure by specifying col and row parameters. Functions like relplot, catplot, and lmplot internally use FacetGrid to arrange their panels.
When using the lower‑level Axes API, the x and y arguments must refer to column names of a DataFrame, while direct Axes calls offer more flexibility. Common Seaborn functions that draw on Axes include sns.scatterplot, sns.lineplot, and sns.barplot.
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
tips = pd.read_csv("dataset/tips.csv")
# scatterplot returns an Axes object
axes = sns.scatterplot(x="total_bill", y="tip", data=tips)
axes.set_xticks(range(0, 60, 5))To create multiple plots in one figure, you can use plt.subplots and pass the resulting Axes objects to Seaborn functions:
fig, [ax1, ax2] = plt.subplots(1, 2, figsize=(20, 5))
# scatter plot on the first Axes
sns.scatterplot(x="total_bill", y="tip", data=tips, ax=ax1)
# bar plot on the second Axes
sns.barplot(x="day", y="total_bill", data=tips, ax=ax2)Basic FacetGrid usage starts with creating a FacetGrid object and calling its map method, where the first argument is a plotting function that accepts color:
g1 = sns.FacetGrid(tips)
g1.map(plt.scatter, "total_bill", "tip")To split the figure by a column, use the col (and optionally row) argument:
g2 = sns.FacetGrid(tips, col="day", col_wrap=2)
g2.map(plt.scatter, "total_bill", "tip")Adding a hue parameter lets you colour‑code another variable, and add_legend() inserts a legend:
g2 = sns.FacetGrid(tips, col="day", hue="time")
g2.map(plt.scatter, "total_bill", "tip")
g2.add_legend()Figure size and aspect ratio can be controlled via the height and aspect arguments of FacetGrid:
g3 = sns.FacetGrid(tips, col="smoker", height=4, aspect=1.5)
g3.map(sns.barplot, "day", "total_bill")Titles for each subplot are set with set_titles. The template string can reference {col_var}, {col_name}, {row_var}, and {row_name} placeholders:
g = sns.FacetGrid(tips, col="day", row="time")
g.map(sns.regplot, "total_bill", "tip")
g.set_titles(template="{col_var}/{col_name}标题")Axis labels are added with set_axis_labels, while other Axes properties (e.g., facecolor, ticks) are modified via the set method:
g.set_axis_labels('消费金额', '小费')
g.set(facecolor='y')
g.set(xticks=range(0, 50, 5),
xticklabels=["$%d" % x for x in range(0, 50, 5)])The underlying Figure object is accessible through g.fig, allowing further adjustments such as DPI:
g.fig.set_dpi(100)Overall, the article provides a comprehensive walkthrough of creating, customizing, and fine‑tuning multi‑panel visualizations with Seaborn's FacetGrid, complete with code snippets and explanations of each configurable parameter.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
