Matplotlib
基础绘图库。优先使用 fig, ax = plt.subplots():Figure 管整张图,Axes 管一个绘图区。
安装与导入
python -m pip install matplotlib numpy
import numpy as np
import matplotlib.pyplot as plt
以下小节共用导入,每个小节单独创建图形。
常用用法
折线图与标签
x = np.arange(1, 6)
loss = [0.9, 0.6, 0.4, 0.3, 0.25]
fig, ax = plt.subplots(figsize=(6, 3.5), layout="constrained")
ax.plot(x, loss, marker="o", color="tab:blue", label="Train")
ax.set(title="Training loss", xlabel="Epoch", ylabel="Loss")
ax.grid(alpha=0.25)
ax.legend()
plt.show()
散点、柱状与直方图
rng = np.random.default_rng(42)
values = rng.normal(size=200)
fig, axes = plt.subplots(1, 3, figsize=(10, 3), layout="constrained")
axes[0].scatter([1, 2, 3], [2, 1, 4], s=30, alpha=0.7)
axes[0].set_title("Scatter")
axes[1].bar(["A", "B", "C"], [3, 5, 4])
axes[1].set_title("Bar")
axes[2].hist(values, bins=20, edgecolor="white")
axes[2].set_title("Histogram")
plt.show()
| 目标 | 方法 |
|---|---|
| 看趋势 | ax.plot |
| 看两变量关系 | ax.scatter |
| 比较类别数量或数值 | ax.bar |
| 看数值分布 | ax.hist |
| 显示二维矩阵或图像 | ax.imshow |
多子图与共享坐标轴
x = np.linspace(0, 2 * np.pi, 100)
fig, axes = plt.subplots(2, 1, sharex=True, figsize=(6, 4), layout="constrained")
axes[0].plot(x, np.sin(x))
axes[0].set_ylabel("sin(x)")
axes[1].plot(x, np.cos(x))
axes[1].set(xlabel="x", ylabel="cos(x)")
plt.show()
保存图片与中文字体
with plt.rc_context({"font.sans-serif": ["Microsoft YaHei", "DejaVu Sans"]}):
fig, ax = plt.subplots(figsize=(5, 3), layout="constrained")
ax.plot([1, 2, 3], [0.6, 0.4, 0.2])
ax.set_title("训练损失")
fig.savefig("loss.png", dpi=200, bbox_inches="tight")
fig.savefig("loss.svg", bbox_inches="tight")
plt.close(fig)
中文字体必须在本机安装;其他系统可换成已安装的 Noto Sans CJK 等字体。PNG 是位图,SVG 适合后期调整。
进阶与不常用用法
两个不同量纲的纵轴
epochs = [1, 2, 3, 4]
fig, ax = plt.subplots(layout="constrained")
other = ax.twinx()
ax.plot(epochs, [0.8, 0.5, 0.3, 0.2], color="tab:blue")
other.plot(epochs, [0.6, 0.7, 0.8, 0.9], color="tab:orange")
ax.set(xlabel="Epoch", ylabel="Loss")
other.set_ylabel("Accuracy")
plt.show()
双轴容易放大视觉相关性,比较趋势前先读清两个刻度。见 twinx。
不规则子图布局
fig, axes = plt.subplot_mosaic(
[["main", "side"], ["main", "bottom"]],
figsize=(7, 4), layout="constrained",
)
axes["main"].plot([1, 2, 3], [1, 4, 2])
axes["side"].bar(["A", "B"], [2, 3])
axes["bottom"].plot([0, 1], [1, 0])
plt.show()
相同名字表示同一个绘图区跨越多个格子,见 subplot_mosaic。
临时修改样式
with plt.rc_context({"axes.spines.top": False, "axes.spines.right": False}):
fig, ax = plt.subplots()
ax.plot([0, 1, 2], [2, 1, 3], linewidth=2)
plt.show()
上下文退出后恢复配置,适合只给一张图换风格。见样式设置。
易错点
plt.subplots()默认会压缩维度:单图返回一个Axes,多图可能返回一维或二维数组;想固定二维可设squeeze=False。- 批量出图后调用
plt.close(fig),及时释放图形资源。 - 保存通常放在
plt.show()前,并使用明确的fig.savefig()。 - 有
label不等于已显示图例,还需要ax.legend()。