import seaborn as sns
tips = sns.load_dataset("tips")
sns.scatterplot(x="total_bill", y="tip", data=tips)技术支持
输出:
可以通过自定义图表的 `hue` 和 `size` 参数来改进这个简单图表。如下所示:
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")# customize the scatter plot
sns.scatterplot(x="total_bill", y="tip", hue="sex", size="size", sizes=(50,200), data=tips)# add labels and title
plt.xlabel("Total Bill")
plt.ylabel("Tip")
plt.title("Relationship between Total Bill and Tip")# display the plot
plt.show()技术支持
import seaborn as sns
fmri = sns.load_dataset("fmri")
sns.lineplot(x="timepoint", y="signal", data=fmri)技术支持
输出:
我们可以使用数据集中的 `event` 和 `region` 列轻松自定义:
import seaborn as sns
import matplotlib.pyplot as plt
fmri = sns.load_dataset("fmri")# customize the line plot
sns.lineplot(x="timepoint", y="signal", hue="event", style="region", markers=True, dashes=False, data=fmri)# add labels and title
plt.xlabel("Timepoint")
plt.ylabel("Signal Intensity")
plt.title("Changes in Signal Intensity over Time")# display the plot
plt.show()技术支持
import seaborn as sns
titanic = sns.load_dataset("titanic")
sns.barplot(x="class", y="fare", data=titanic)技术支持
输出:
我们将通过加入数据集中的 `sex` 列来自定义此图表。
import seaborn as sns
import matplotlib.pyplot as plt
titanic = sns.load_dataset("titanic")# customize the bar plot
sns.barplot(x="class", y="fare", hue="sex", errorbar=None, palette="muted", data=titanic)# add labels and title
plt.xlabel("Class")
plt.ylabel("Fare")
plt.title("Average Fare by Class and Gender on the Titanic")# display the plot
plt.show()技术支持
import seaborn as sns
iris = sns.load_dataset("iris")
sns.histplot(x="petal_length", data=iris)技术支持
输出:
自定义直方图
import seaborn as sns
import matplotlib.pyplot as plt
iris = sns.load_dataset("iris")# customize the histogram
sns.histplot(data=iris, x="petal_length", bins=20, kde=True, color="green")# add labels and title
plt.xlabel("Petal Length (cm)")
plt.ylabel("Frequency")
plt.title("Distribution of Petal Lengths in Iris Flowers")# display the plot
plt.show()技术支持
输出:
创建 Seaborn 密度图
密度图(也称核密度估计或 KDE 图)以平滑曲线而非离散箱体来展示连续变量的分布。当您希望比较分布、又不想受直方图箱宽影响时,它很有用。在 Seaborn 中使用 kdeplot() 创建。
import seaborn as sns
tips = sns.load_dataset("tips")
sns.kdeplot(data=tips, x="total_bill")技术支持
输出:
我们通过自定义来改进该图表。
import seaborn as sns
import matplotlib.pyplot as plt
# Load the "tips" dataset from Seaborn
tips = sns.load_dataset("tips")# Create a density plot of the "total_bill" column from the "tips" dataset# We use the "hue" parameter to differentiate between "lunch" and "dinner" meal times# We use the "fill" parameter to fill the area under the curve# We adjust the "alpha" and "linewidth" parameters to make the plot more visually appealing
sns.kdeplot(data=tips, x="total_bill", hue="time", fill=True, alpha=0.6, linewidth=1.5)# Add a title and labels to the plot using Matplotlib
plt.title("Density Plot of Total Bill by Meal Time")
plt.xlabel("Total Bill ($)")
plt.ylabel("Density")# Show the plot
plt.show()技术支持
输出:
创建 Seaborn 箱线图
箱线图用于展示数据集的分布,常用于比较一个或多个变量在不同类别下的分布情况。
import seaborn as sns
tips = sns.load_dataset("tips")
sns.boxplot(x="day", y="total_bill", data=tips)技术支持
输出:
通过加入数据集中的 `time` 列来自定义箱线图。
import seaborn as sns
import matplotlib.pyplot as plt
# load the tips dataset from Seaborn
tips = sns.load_dataset("tips")# create a box plot of total bill by day and meal time, using the "hue" parameter to differentiate between lunch and dinner# customize the color scheme using the "palette" parameter# adjust the linewidth and fliersize parameters to make the plot more visually appealing
sns.boxplot(x="day", y="total_bill", hue="time", data=tips, palette="Set3", linewidth=1.5, fliersize=4)# add a title, xlabel, and ylabel to the plot using Matplotlib functions
plt.title("Box Plot of Total Bill by Day and Meal Time")
plt.xlabel("Day of the Week")
plt.ylabel("Total Bill ($)")# display the plot
plt.show()技术支持
import seaborn as sns
import matplotlib.pyplot as plt
# Load the dataset
tips = sns.load_dataset('tips')# Create a heatmap of the correlation between variables
corr = tips.select_dtypes(include="number").corr()
sns.heatmap(corr, annot=True, cmap="coolwarm")# Show the plot
plt.show()技术支持
输出:
以下是使用 `flights` 数据集的另一个热力图示例。
import seaborn as sns
import matplotlib.pyplot as plt
# Load the dataset
flights = sns.load_dataset('flights')# Pivot the data
flights = flights.pivot(index="month", columns="year", values="passengers")# Create a heatmap
sns.heatmap(flights, cmap='Blues', annot=True, fmt='d')# Set the title and axis labels
plt.title('Passengers per month')
plt.xlabel('Year')
plt.ylabel('Month')# Show the plot
plt.show()技术支持
import seaborn as sns
# load the tips dataset
tips = sns.load_dataset('tips')# create a FacetGrid for day vs total_bill
g = sns.FacetGrid(tips, col="day")# plot histogram for total_bill in each day
g.map(sns.histplot,"total_bill")技术支持
import seaborn as sns
import matplotlib.pyplot as plt
# Load sample dataset
tips = sns.load_dataset("tips")# Create a scatter plot with color palette
sns.scatterplot(x="total_bill", y="tip", hue="day", data=tips, palette="Set2")# Customize plot
plt.title("Total Bill vs Tip")
plt.xlabel("Total Bill ($)")
plt.ylabel("Tip ($)")
plt.show()技术支持
输出:
调整图形尺寸
若要调整 Seaborn 图表的尺寸,可参考以下示例:
import seaborn as sns
import matplotlib.pyplot as plt
# Load sample dataset
iris = sns.load_dataset("iris")# Create a violin plot with adjusted figure size
plt.figure(figsize=(8,6))
sns.violinplot(x="species", y="petal_length", data=iris)# Customize plot
plt.title("Petal Length Distribution by Species")
plt.xlabel("Species")
plt.ylabel("Petal Length (cm)")
plt.show()技术支持
输出:
添加注释
注释有助于提升可视化的可读性。以下示例展示了如何添加注释:
import seaborn as sns
import matplotlib.pyplot as plt
# Load sample dataset
diamonds = sns.load_dataset("diamonds")# Create a scatter plot with annotations
sns.scatterplot(x="carat", y="price", data=diamonds)# Add annotations
plt.text(1,18000,"Large, Expensive Diamonds", fontsize=12, color="red")
plt.text(2.5,5000,"Small, Affordable Diamonds", fontsize=12, color="blue")# Customize plot
plt.title("Diamond Prices by Carat")
plt.xlabel("Carat (ct)")
plt.ylabel("Price ($)")
plt.show()技术支持
Seaborn 是用于统计数据可视化的常用 Python 库之一。它基于 Matplotlib 构建,能以更少的代码生成精致图表;与 pandas DataFrame 无缝集成,并通过一致的 API 处理常见统计图表——直方图、箱线图、热力图、回归拟合等。
在本教程中,我将介绍 Seaborn 的核心图表类型,展示如何自定义它们,并将 Seaborn 与 Matplotlib、Plotly 等其他 Python 可视化库进行比较。所有代码示例均使用 Seaborn 0.13+ 和 pandas 2.0+。
要点速览
Seaborn 是基于 Matplotlib 的 Python 统计可视化库——使用
pip install seaborn安装可直接配合 pandas DataFrame 使用:将列名作为
x、y和hue参数传入关键图表类型:
scatterplot()、lineplot()、barplot()、histplot()、boxplot()、heatmap()、pairplot()图级函数(
relplot()、displot()、catplot())一次调用即可创建多面板网格使用
set_theme()和内置配色方案自定义外观什么是 Seaborn?
Seaborn 是构建在 Matplotlib 之上的 Python 数据可视化库。它可直接与 pandas DataFrame 协同工作,因此您传入的是列名而非原始数组。该库覆盖了最常见的统计图表类型:散点图、折线图、条形图、直方图、箱线图、热力图等。
Seaborn 将其 API 组织为三个层级:
图级函数(
relplot()、displot()、catplot())创建整张图形网格并自动处理分面坐标轴级函数(如
scatterplot()、histplot()、boxplot()等)绘制到单个 Matplotlib 坐标轴上实用函数(
heatmap()、pairplot()、jointplot())用于特定的多面板布局您可以通过我们的 Introduction to Data Visualization with Seaborn 课程进一步学习 Seaborn。
Seaborn 自带内置主题和 配色方案,只需一次
set_theme()调用即可应用。它还包含统计估计——如条形图上的置信区间、回归拟合、核密度估计——让您用最少的代码就能从原始数据生成可发表级别的图形。图片来源
Seaborn vs. Matplotlib
Python 中最常用的两大可视化库是 Matplotlib 和 Seaborn。二者都能创建高质量图形与可视化,但在若干关键点上各有所长,适用于不同场景。
Matplotlib 让您可完全控制图形中的每个元素(坐标轴、刻度、图例、注释),但这种控制意味着每张图需要更多代码。Seaborn 以牺牲部分粒度换取速度:对 DataFrame 一次函数调用即可生成带样式的统计图。
subplots()手动实现FacetGrid、relplot()自动实现实践中,您会将两者结合使用。由 Seaborn 生成图表,再用 Matplotlib 函数微调标签、范围或注释——下面示例中将会看到。
您可通过我们的 Introduction to Plotting with Matplotlib in Python 教程更深入了解 Matplotlib。
安装 Seaborn
Seaborn(自 0.13 起)需要 Python 3.9+,并依赖 Matplotlib、pandas 和 NumPy。可通过 pip 或 conda 安装:
使用 pip 时,会安装 Seaborn 及其必需依赖。若想启用附加的可选功能,还可在 pip 安装时包含可选依赖。例如:
或使用 conda:
示例数据集
Seaborn 提供了若干内置数据集,便于进行数据可视化与统计分析。这些数据集以 pandas DataFrame 形式存储,便于与 Seaborn 的绘图函数配合使用。
最常见、且在 Seaborn 官方示例中广泛使用的数据集之一是“tips 数据集”,包含餐厅小费信息。以下是使用 Seaborn 加载并可视化 Tips 数据集的示例:
输出:
如果您还不理解这个图——别担心。这叫直方图。我们会在后文更详细地解释直方图。目前需要记住的是,Seaborn 自带了大量以 pandas DataFrame 形式提供的示例数据集,便于您上手并练习可视化技能。以下是加载 `exercise` 数据集的另一个示例。
输出:
Seaborn 图表类型
Seaborn 为不同分析需求提供了多种图表类型。一般来说,可视化大致归为三类:
图片来源
以下是 Seaborn 中一些最常用的图表类型:
接下来一节将通过示例对上述每种图表进行详细说明。
图级函数 vs. 坐标轴级函数
Seaborn 中最重要的概念之一是区分图级函数与坐标轴级函数。理解这一点能为您节省大量调试时间。
坐标轴级函数(如
scatterplot()、histplot()、boxplot())绘制到单个 Matplotlib 坐标轴上。您可以传入ax参数来控制绘制位置:图级函数(
relplot()、displot()、catplot())会自行创建图形,并可使用col与row参数自动将数据分为多个面板:图级函数返回的是
FacetGrid对象而非坐标轴,因此设置标题与标签的方式不同:使用g.set_axis_labels()和g.set_titles(),而不是plt.xlabel()。如何在 Seaborn 中创建图表
下面通过几个不同图表类型的示例来展示 Seaborn 的用法。
创建 Seaborn 散点图
散点图用于可视化两个连续变量之间的关系。图中的每个点代表一个数据点,其在 x 轴和 y 轴上的位置分别表示两个变量的取值。
可通过不同颜色和标记自定义图表,以便区分不同的数据分组。在 Seaborn 中,可使用
scatterplot()函数创建散点图。输出:
可以通过自定义图表的 `hue` 和 `size` 参数来改进这个简单图表。如下所示:
输出:
创建 Seaborn 折线图
折线图用于可视化数据随时间或其他连续变量的趋势。在折线图中,各数据点由线段连接,形成平滑曲线。在 Seaborn 中,可使用
lineplot()函数创建折线图。可参阅我们的 Seaborn 折线图教程 深入了解。输出:
我们可以使用数据集中的 `event` 和 `region` 列轻松自定义:
输出:
同样,这里我用 Seaborn 绘制基础折线图,并用 Matplotlib 添加坐标轴标签与标题。
创建 Seaborn 条形图
条形图用于可视化类别变量与连续变量之间的关系。在条形图中,每个柱表示该类别上连续变量的均值、中位数(或任意聚合)。在 Seaborn 中,可使用
barplot()函数创建条形图。更多详情参见我们的 Seaborn 条形图指南。输出:
我们将通过加入数据集中的 `sex` 列来自定义此图表。
输出:
创建 Seaborn 直方图
直方图用于可视化连续变量的分布。直方图将数据划分为若干箱(bin),每个箱的高度表示该区间内数据点的频数或计数。在 Seaborn 中,可使用
histplot()函数创建直方图。我们的 Seaborn 直方图指南对此有更深入讲解。输出:
自定义直方图
输出:
创建 Seaborn 密度图
密度图(也称核密度估计或 KDE 图)以平滑曲线而非离散箱体来展示连续变量的分布。当您希望比较分布、又不想受直方图箱宽影响时,它很有用。在 Seaborn 中使用
kdeplot()创建。输出:
我们通过自定义来改进该图表。
输出:
创建 Seaborn 箱线图
箱线图用于展示数据集的分布,常用于比较一个或多个变量在不同类别下的分布情况。
输出:
通过加入数据集中的 `time` 列来自定义箱线图。
创建 Seaborn 小提琴图
小提琴图是一种结合了箱线图与密度图特征的可视化形式。它展示了基于核密度估计的平滑分布曲线,同时以类似箱线图的形式呈现四分位距(IQR)和中位数。
小提琴的宽度代表密度估计,越宽表示密度越高;IQR 和中位数通常在小提琴内部以白点与线条显示。
输出:
创建 Seaborn 热力图
热力图使用颜色表示矩阵中的数值。在数据分析中,热力图常用于可视化相关矩阵。我们的 Seaborn 热力图指南涵盖高级自定义选项。
输出:
以下是使用 `flights` 数据集的另一个热力图示例。
输出:
在此示例中,我们使用 `seaborn` 库中的 `flights` 数据集。我们通过
.pivot()方法对数据进行透视,使其适合热力图展示。随后使用sns.heatmap()函数创建热力图,并将透视后的 flights 变量作为参数传入。创建 Seaborn 成对关系图
成对关系图以矩阵形式展示多个两两散点图。每个散点图显示两个变量之间的关系,而对角线上的图显示各单变量的分布。
输出:
我们可以通过 `hue` 和 `diag_kind` 参数自定义此图。
输出:
创建 Seaborn 联合分布图
联合分布图在同一图形中结合了散点图(中心)与边际直方图(顶部与右侧边缘)。这种布局让您能一目了然地看到两个变量之间的关系及其各自的分布。
以下是使用 iris 数据集构建 seaborn 联合分布图的简单示例:
输出:
创建 Seaborn 分面网格
FacetGrid会根据分类变量的唯一取值创建由多个子图构成的网格。这能让您在不同分组间对同一图表进行对比(例如,每周不同日期的总账单分布)。输出:
Python Seaborn 速查表
这份包含代码示例的 Python Seaborn 速查表,将带您快速上手这一基于 Matplotlib 的数据可视化库。
Seaborn 主题与样式
Seaborn 提供了五种内置主题,可控制图表的整体外观。您可在脚本开头调用
sns.set_theme()进行全局应用:您还可通过
context参数控制图形元素的尺度。它会根据不同输出格式调整字号、线宽等元素:"notebook"上下文(默认)适合 Jupyter 笔记本,而"talk"与"poster"会将一切按演示需求放大。自定义 Seaborn 图表
除了默认样式,Seaborn 还提供对配色方案、图形尺寸、主题和注释等的控制。以下是最常见的自定义方式:
更改配色方案
下面示例展示如何更改 Seaborn 图表的配色方案:
输出:
调整图形尺寸
若要调整 Seaborn 图表的尺寸,可参考以下示例:
输出:
添加注释
注释有助于提升可视化的可读性。以下示例展示了如何添加注释:
输出:
Seaborn 可视化最佳实践
以下是充分发挥 Seaborn 价值的若干最佳实践。
为数据选择合适的图表类型
Seaborn 提供了多种图表类型,分别适用于不同的数据与分析。为数据选对图表类型对于有效传达结论至关重要。例如,散点图更适合展示两个连续变量之间的关系,而条形图更适合展示分类数据。
有效使用颜色
颜色是强有力的可视化工具,但务必谨慎使用。避免使用过多或过于鲜艳的颜色,以免影响阅读。应使用颜色突出重要信息或对相似数据点分组。
标注坐标轴并使用清晰标题
标签与标题是高效数据可视化的要素。请清晰标注坐标轴并提供描述性标题,帮助受众理解您要传达的信息。
考虑受众
创建可视化时,应考虑受众及您要传递的信息。若受众并非技术背景,请使用清晰简洁的语言,避免技术术语,并对统计概念做出清楚解释。
使用合适的统计分析
Seaborn 提供了多种统计函数可用于分析数据。选择统计函数时,请确保与您的数据与研究问题相匹配。
自定义您的可视化
Seaborn 提供了丰富的自定义选项,可用于增强可视化。尝试不同的字体、样式与配色,找到最能传达您信息的呈现方式。
选择合适的 Python 可视化库
在以上基础上,来看 Seaborn 与 Matplotlib 及您可能遇到的另两种替代方案的对比,以及各自适用场景:
.plot()在大多数数据分析工作中,我会用 Seaborn 进行初步探索,用 Matplotlib 做精细调整,而当输出需要交互时使用 Plotly。它们并不互斥。
结语
Seaborn 是一款功能强大的 Python 数据可视化库,提供直观易用的接口以创建信息丰富的统计图形。凭借其丰富的可视化工具,Seaborn 能够帮助您快速高效地从复杂数据集中探索并传达洞见。
从散点图与折线图,到热力图与分面网格,Seaborn 提供了多种可视化以满足不同需求。此外,Seaborn 与 Pandas、Numpy 的集成也使其成为数据分析师与数据科学家的必备工具。
借助这份 Python Seaborn 新手指南,您可以开始探索数据可视化的世界,并将洞见有效传达给更广泛的受众。
如果您希望进一步拓展相关知识,请查看我们的 Introduction to Data Visualization with Seaborn 或 Intermediate Data Visualization with Seaborn 课程。
在这些课程中,您将学习如何利用 Seaborn 的高级可视化工具来分析多种真实世界数据集,例如美国住房调查、大学学费数据,以及 The Daily Show 的来宾数据。
您也可以查看我们的免费 Seaborn 速查表。