1. 三个库的定位
| 对比 | Matplotlib | Seaborn | Plotly |
|---|---|---|---|
| 定位 | 通用绘图基础库 | 统计可视化 | 交互式可视化 |
| 主要特点 | 控制能力强 | 代码简洁、统计功能丰富 | Hover、Zoom、交互 |
| Pandas 集成 | 支持 | 非常紧密 | 非常紧密 |
| 静态图表 | 强 | 强 | 支持 |
| 交互式图表 | 有限,依赖后端 | 主要继承 Matplotlib | 核心能力 |
| 典型用途 | 科研图表、精细布局 | EDA、分布与关系分析 | Dashboard、Web 图表 |
常见导入:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.express as px
import plotly.graph_objects as go
示例数据:
rng = np.random.default_rng(42)
df = pd.DataFrame({
"group": np.repeat(["A", "B", "C"], 100),
"x": rng.normal(size=300),
"y": rng.normal(size=300),
"value": rng.normal(loc=50, scale=10, size=300),
})
2. 如何选择图表
不同图表适合回答不同问题。
| 分析目的 | 推荐图表 |
|---|---|
| 时间变化趋势 | Line Plot |
| 类别间比较 | Bar Plot |
| 单变量分布 | Histogram、KDE |
| 分布差异与异常值 | Box Plot、Violin Plot |
| 两个连续变量的关系 | Scatter Plot |
| 多变量相关性 | Heatmap |
| 多组变量关系 | Pair Plot |
| 累计量与组成变化 | Stacked Bar / Area |
| 空间分布 | Scatter Map / Geographic Map |
不应该只根据图表是否美观进行选择,首先应确定要表达的数据关系。
例如,两个连续变量的相关性使用 Scatter Plot 通常比 Line Plot 更合适。
3. Matplotlib:Figure 与 Axes
Matplotlib 最重要的概念是 Figure 和 Axes。
Figure
└── Axes
├── X / Y Axis
├── Title
├── Lines / Bars / Markers
├── Legend
└── Grid
- Figure:整个画布。
- Axes:画布中的一个绘图区域,包含坐标轴和图形元素。
- Axis:具体的 X、Y 坐标轴及刻度。
推荐使用面向对象 API:
fig, ax = plt.subplots(figsize=(8, 5))
ax.plot([1, 2, 3, 4], [10, 15, 13, 20])
ax.set(
title="Sales Trend",
xlabel="Month",
ylabel="Sales",
)
ax.grid(alpha=0.3)
plt.show()
与直接使用 plt.plot() 相比,fig, ax = plt.subplots() 更适合构建多子图和可复用的绘图函数。
常见绘图函数
ax.plot(x, y) # 折线图
ax.scatter(x, y) # 散点图
ax.bar(x, y) # 柱状图
ax.barh(x, y) # 横向柱状图
ax.hist(data) # 直方图
ax.boxplot(data) # 箱线图
ax.imshow(matrix) # 矩阵 / 图像
样式和标注
fig, ax = plt.subplots()
ax.plot(
[1, 2, 3],
[10, 15, 13],
label="Product A",
color="steelblue",
linestyle="--",
marker="o",
linewidth=2,
)
ax.set_title("Sales")
ax.set_xlabel("Month")
ax.set_ylabel("Revenue")
ax.legend()
ax.grid(alpha=0.3)
常用属性:
color:颜色。linestyle:线型。linewidth:线宽。marker:数据点标记。alpha:透明度。label:图例名称。
Subplots:多子图
fig, axes = plt.subplots(
nrows=1,
ncols=2,
figsize=(10, 4),
layout="constrained",
)
axes[0].plot([1, 2, 3], [2, 4, 3])
axes[0].set_title("Line")
axes[1].bar(["A", "B", "C"], [10, 20, 15])
axes[1].set_title("Bar")
plt.show()
layout="constrained" 可以帮助自动调整子图和标签的空间。
保存图片
fig.savefig(
"chart.png",
dpi=300,
bbox_inches="tight",
)
fig.savefig(
"chart.svg",
bbox_inches="tight",
)
- PNG:适合普通图片、文档。
- SVG:适合矢量图和网页。
- PDF:适合报告和论文。
对于静态图表,Matplotlib 通常是首选。
4. Seaborn:统计可视化
Seaborn 基于 Matplotlib 构建,主要优势是能够直接使用 Pandas DataFrame,并自动处理分类变量、颜色映射和部分统计计算。
sns.set_theme(style="whitegrid")
Scatter Plot
sns.scatterplot(
data=df,
x="x",
y="y",
hue="group",
)
plt.show()
Semantic Mapping
Seaborn 可以将数据列映射为不同的视觉属性:
| 参数 | 作用 |
|---|---|
x / y | 坐标位置 |
hue | 颜色分组 |
style | 标记或线型 |
size | 点大小或线宽 |
sns.scatterplot(
data=df,
x="x",
y="y",
hue="group",
style="group",
)
这一机制适合探索多个变量之间的关系。
5. 数据分布可视化
分析数据时,分布通常比均值更值得关注。
Histogram
sns.histplot(
data=df,
x="value",
bins=25,
)
展示数值的频数分布。
KDE:Kernel Density Estimation
sns.kdeplot(
data=df,
x="value",
hue="group",
fill=True,
)
KDE 使用核密度估计构造平滑的概率密度曲线。
它不是实际频数,平滑程度也会影响对数据的解释。
Box Plot
sns.boxplot(
data=df,
x="group",
y="value",
)
Box Plot 通常展示:
- 中位数。
- 第一、第三四分位数。
- 四分位距(IQR)。
- Whiskers。
- 超出 Whisker 的数据点。
Whisker 不一定是样本的最大值和最小值,具体取决于绘图规则。
Violin Plot
sns.violinplot(
data=df,
x="group",
y="value",
)
Violin Plot 将箱线图相关信息与密度分布形状结合起来,适合比较多个组的分布。
| 图表 | 优势 |
|---|---|
| Histogram | 直接观察频数 |
| KDE | 平滑观察分布形状 |
| Box Plot | 比较中位数、离散程度、异常点 |
| Violin Plot | 比较组间分布形状 |
6. 类别比较与统计关系
Bar Plot
sns.barplot(
data=df,
x="group",
y="value",
estimator="mean",
errorbar="sd",
)
这里有一个重要区别:
- Matplotlib
ax.bar():直接绘制传入的高度。 - Seaborn
sns.barplot():默认会对每个类别的数据进行统计聚合。
Seaborn 的 barplot() 默认使用均值作为估计量,并默认显示置信区间。
如果需要显示每组样本数量,可以先聚合,再绘图:
counts = df["group"].value_counts()
sns.barplot(
x=counts.index,
y=counts.values,
)
也可以使用:
sns.countplot(
data=df,
x="group",
)
Regression Plot
sns.regplot(
data=df,
x="x",
y="y",
)
适合快速探索线性趋势和变量关系。
但 regplot() 的可视化拟合不应直接替代正式的统计建模和模型诊断。
7. Heatmap 与 Pairplot
Heatmap
经常用于展示相关系数矩阵:
corr = df[["x", "y", "value"]].corr()
sns.heatmap(
corr,
annot=True,
cmap="coolwarm",
vmin=-1,
vmax=1,
center=0,
)
参数:
annot=True:显示数值。cmap:颜色映射。vmin/vmax:固定颜色范围。center:设置颜色中心值。
Pairplot
sns.pairplot(
data=df,
vars=["x", "y", "value"],
hue="group",
)
Pairplot 可以快速展示多个数值变量两两之间的关系,以及每个变量自身的分布。
适合 EDA(Exploratory Data Analysis),但变量数量过多时会产生大量子图。
8. Seaborn 的 Axes-level 与 Figure-level
这是 Seaborn 一个比较重要的设计区别。
Axes-level Functions
在指定 Matplotlib Axes 上绘图:
fig, ax = plt.subplots()
sns.histplot(
data=df,
x="value",
ax=ax,
)
ax.set_title("Distribution")
常见函数:
scatterplot
lineplot
histplot
kdeplot
boxplot
violinplot
barplot
heatmap
Figure-level Functions
直接管理整个 Figure,支持分面布局:
g = sns.relplot(
data=df,
x="x",
y="y",
col="group",
kind="scatter",
)
主要包括:
| Figure-level | 主要用途 |
|---|---|
relplot() | Scatter / Line |
displot() | Histogram / KDE / ECDF |
catplot() | 分类图表 |
lmplot() | 回归关系 |
Figure-level 函数通常创建自己的 Figure,不能像 Axes-level 函数那样简单传入已有的 ax。
日常简单图表,优先使用 Axes-level;需要 Faceting 时使用 Figure-level。
9. Plotly:交互式可视化
Plotly 主要用于生成交互式图表,支持:
- Hover Tooltip。
- Zoom / Pan。
- Legend Interaction。
- 图表缩放与导出。
- 交互式 3D / Map。
- HTML 输出。
Plotly 常见两个接口:
- Plotly Express(
px):高级接口,适合大多数常见图表。 - Graph Objects(
go):底层接口,提供更精细的控制。
Plotly Express 创建的图表本身也是 graph_objects.Figure,因此可以在创建后继续修改。
Plotly Express
fig = px.scatter(
df,
x="x",
y="y",
color="group",
hover_data=["value"],
title="Interactive Scatter Plot",
)
fig.show()
常见绘图函数:
px.line(...)
px.scatter(...)
px.bar(...)
px.histogram(...)
px.box(...)
px.violin(...)
px.imshow(...)
px.scatter_matrix(...)
交互式折线图
trend = pd.DataFrame({
"date": pd.date_range("2026-01-01", periods=12, freq="MS"),
"sales": [10, 15, 13, 18, 22, 21, 25, 30, 28, 35, 40, 45],
})
fig = px.line(
trend,
x="date",
y="sales",
markers=True,
title="Monthly Sales",
)
fig.show()
Plotly 默认提供 Hover 和缩放等交互能力,不需要手动编写 JavaScript。
10. Plotly Graph Objects
当需要不同类型的 Trace、复杂布局或高度定制时,可以使用 Graph Objects。
Figure / Trace / Layout
Figure
├── Data
│ ├── Scatter Trace
│ └── Bar Trace
└── Layout
├── Title
├── Axes
├── Legend
└── Annotations
示例:
fig = go.Figure()
fig.add_trace(
go.Scatter(
x=[1, 2, 3],
y=[10, 15, 20],
mode="lines+markers",
name="Product A",
)
)
fig.add_trace(
go.Scatter(
x=[1, 2, 3],
y=[8, 12, 18],
mode="lines+markers",
name="Product B",
)
)
fig.update_layout(
title="Sales Comparison",
xaxis_title="Month",
yaxis_title="Sales",
)
fig.show()
更新已有图表
Plotly Express 创建的 Figure 也可以继续修改:
fig = px.scatter(df, x="x", y="y")
fig.update_traces(marker_size=8)
fig.update_layout(
title="Scatter Plot",
template="plotly_white",
)
fig.update_xaxes(title="X Value")
fig.update_yaxes(title="Y Value")
Subplots
from plotly.subplots import make_subplots
fig = make_subplots(
rows=1,
cols=2,
subplot_titles=["Line", "Bar"],
)
fig.add_trace(
go.Scatter(x=[1, 2, 3], y=[2, 4, 3]),
row=1,
col=1,
)
fig.add_trace(
go.Bar(x=["A", "B"], y=[10, 20]),
row=1,
col=2,
)
fig.show()
需要简单交互图表时,优先使用 Plotly Express;只有需要精细控制时才转向 Graph Objects。
11. Plotly 的 Hover、Facet 与导出
自定义 Hover
fig = px.scatter(
df,
x="x",
y="y",
color="group",
hover_data=["value"],
hover_name="group",
)
Facet
fig = px.scatter(
df,
x="x",
y="y",
facet_col="group",
)
相当于按分类变量拆成多个子图。
HTML 输出
fig.write_html("chart.html")
可以生成可交互的 HTML 图表。
静态图片
fig.write_image("chart.png")
fig.write_image("chart.svg")
静态图片导出通常需要安装和配置 Kaleido 等依赖;当前版本还可能要求 Chrome/Chromium。
12. 数据可视化的重要原则
正确选择轴范围
柱状图通常适合从零开始,以避免夸大类别差异。
折线图则可以根据分析目标合理设置纵轴范围,但需要明确展示尺度。
注意数据聚合
例如使用 sns.barplot() 时,绘制的可能是组均值,而不是原始数据。
应明确:
Count
Mean
Median
Sum
Percentage
不同聚合方式表达的含义完全不同。
避免 Overplotting
如果有几十万个散点:
ax.scatter(x, y, alpha=0.1, s=3)
可以通过透明度和点大小缓解重叠。
也可以考虑:
- Hexbin。
- 2D Histogram。
- 数据抽样。
- Density Plot。
大量交互式数据点可能造成浏览器渲染压力。Plotly 可以在适用场景使用 WebGL Trace,但并不代表无限数据量都能流畅渲染。
颜色映射
常见类型:
| 类型 | 场景 |
|---|---|
| Sequential | 数值从低到高 |
| Diverging | 有意义的中心点,例如相关系数零点 |
| Categorical | 不同类别,没有大小顺序 |
应尽量选择具有可辨识度、适合色觉差异用户的配色方案。
标注与可复现性
图表应包含:
- 清晰标题。
- 轴名称。
- 单位。
- 必要的图例。
- 数据来源(正式报告中)。
- 明确的统计口径。
对于分析报告,应固定筛选条件和聚合逻辑,让图表能够从原始数据重新生成。
13. 三者如何选择
| 使用场景 | 推荐 |
|---|---|
| 简单折线图、散点图 | Matplotlib |
| 论文、静态报告 | Matplotlib |
| DataFrame EDA | Seaborn |
| 数据分布、分组比较 | Seaborn |
| 相关系数矩阵 | Seaborn |
| Notebook 交互探索 | Plotly |
| HTML 交互图表 | Plotly |
| Python Dashboard | Plotly + Dash / Streamlit |
| 精细多子图布局 | Matplotlib / Plotly Graph Objects |
推荐的使用组合
Pandas
↓
Data Cleaning / Aggregation
↓
Visualization
├── Matplotlib → Static Plot
├── Seaborn → Statistical Plot
└── Plotly → Interactive Plot
实际上不需要所有图表都用三个库分别实现。
常见工作流程:
- Pandas 负责清洗和聚合。
- Seaborn 快速探索数据分布和相关性。
- Matplotlib 调整静态图表样式。
- Plotly 制作需要交互的最终图表。
总结
| 知识点 | 重要程度 |
|---|---|
| Matplotlib Figure / Axes | 核心 |
plt.subplots() | 核心 |
| Line / Scatter / Bar / Histogram | 核心 |
| Matplotlib 样式、标签、保存 | 高频 |
Seaborn hue / style / size | 核心 |
Seaborn histplot / boxplot / kdeplot | 核心 |
Seaborn heatmap / pairplot | 高频 |
| Axes-level / Figure-level | 重要 |
| Plotly Express | 核心 |
| Plotly Graph Objects | 重要 |
| Hover / Facet / HTML Export | 高频 |
| 图表选择与统计口径 | 核心 |
最重要的三个概念:
- Matplotlib 的 Figure/Axes 模型:掌握画布、子图与图形元素之间的关系。
- Seaborn 的 Statistical Visualization:利用 DataFrame 和语义映射快速探索变量关系与数据分布。
- Plotly 的 Figure/Trace/Layout 模型:通过声明式数据结构创建交互式图表。
对于日常数据分析,熟悉 Matplotlib 和 Seaborn 已能完成绝大部分静态可视化工作;当需要 Hover、Zoom、动态筛选或 HTML 交互展示时,再使用 Plotly。