Seaborn
基于 Matplotlib 的统计绘图库,适合直接从 Pandas 表格绘图。精细调整坐标轴时仍会用到 Matplotlib。
安装与准备
python -m pip install seaborn pandas matplotlib
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme(style="whitegrid", palette="Blues")
df = pd.DataFrame({
"hours": [1, 2, 3, 4, 5, 1, 2, 3, 4, 5],
"score": [55, 61, 70, 75, 82, 59, 65, 72, 81, 88],
"method": ["A"] * 5 + ["B"] * 5,
})
后续示例共用这份本地数据,不需要下载示例数据集。
常用用法
散点图:关系与分组
fig, ax = plt.subplots(figsize=(5, 3), layout="constrained")
sns.scatterplot(data=df, x="hours", y="score", hue="method", style="method", ax=ax)
ax.set_title("Study hours and score")
plt.show()
hue 用颜色区分组,style 用形状区分组;见关系图教程。
折线图:比较趋势
fig, ax = plt.subplots(layout="constrained")
sns.lineplot(
data=df, x="hours", y="score", hue="method",
marker="o", errorbar=None, ax=ax,
)
plt.show()
同一组在同一个 x 上有多个观测时,lineplot 默认聚合均值;若想逐条连线,要另设 estimator=None 并考虑 units。
直方图:观察分布
fig, ax = plt.subplots(layout="constrained")
sns.histplot(data=df, x="score", hue="method", bins=6, multiple="dodge", ax=ax)
plt.show()
bins 控制分箱。数据少时,分箱数量会明显影响视觉印象,见分布图教程。
柱状图与箱线图
fig, axes = plt.subplots(1, 2, figsize=(8, 3), layout="constrained")
sns.barplot(data=df, x="method", y="score", errorbar="sd", ax=axes[0])
sns.boxplot(data=df, x="method", y="score", ax=axes[1])
plt.show()
本例柱高为均值,误差条为标准差;箱线图展示分位数等分布信息。统计选项见 barplot。
进阶与不常用用法
相关系数热力图
corr = df[["hours", "score"]].corr()
fig, ax = plt.subplots(layout="constrained")
sns.heatmap(corr, annot=True, fmt=".2f", vmin=-1, vmax=1, cmap="vlag", ax=ax)
plt.show()
固定 vmin、vmax 便于比较多张图;相关关系不能证明因果,见 heatmap。
分面:一组数据一张小图
grid = sns.relplot(
data=df, x="hours", y="score", col="method",
kind="scatter", height=3, aspect=1,
)
grid.set_axis_labels("Hours", "Score")
grid.savefig("score-by-method.png", dpi=200)
plt.show()
分面图会自己创建整张画布,适合并排比较子集。
分清 Axes 级与 Figure 级接口
| 接口类型 | 例子 | 调整方式 |
|---|---|---|
| Axes 级 | scatterplot、histplot、boxplot | 传入 ax=,可放进现有子图 |
| Figure 级 | relplot、displot、catplot | 创建自己的画布,通过返回的 grid 调整 |
两类接口的组织方式见绘图函数总览。
易错点
barplot默认做数值统计;想看每类有多少条记录,使用countplot。- 不要给 Figure 级函数硬塞已有的
ax。 - 均值、标准差、置信区间含义不同,画图前先确定要表达什么。
- Seaborn 与 Matplotlib 的全局主题可能互相影响;需要局部配置时使用上下文管理器。