matplotlib 用法大全
按功能分类的字典。每个函数列常用参数和一个能跑的例。 两种接口、画布骨架、保存、中文在入门那课。
所有代码假定已有:
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()一、常用图类型
plot —— 折线
参数 | 作用 |
|---|---|
| 数据 |
| 颜色 |
| 线型 |
| 线宽 |
| 标记符号 |
| 标记大小 |
| 透明度 0~1 |
| 图例名 |
| 图层顺序(大的在上) |
x = np.linspace(0, 10, 100)
ax.plot(x, np.sin(x), color="#58a6ff", lw=2, label="sin")
ax.plot(x, np.cos(x), "r--", lw=1.5, label="cos")scatter —— 散点
参数 | 作用 |
|---|---|
| 点大小(面积) |
| 颜色(可以是数组,配合 cmap) |
| 色表名 |
| 形状 |
| 描边颜色 |
| 描边宽度 |
| 色标范围 |
ax.scatter(x, y, s=30, c=y, cmap="viridis", alpha=.8)
ax.scatter(x, y, s=30, c="red", edgecolors="white", linewidths=.5)bar / barh —— 柱状
参数 | 作用 |
|---|---|
| 位置、高度 |
| 柱子宽度(默认 0.8) |
| 堆叠时的底部 |
|
|
| 可以是颜色列表 |
城市 = ["北京", "上海", "广州"]
销量 = [30, 50, 20]
ax.bar(城市, 销量, width=.6, color="#58a6ff")
ax.barh(城市, 销量) # 横向
# 堆叠柱
ax.bar(城市, [20,30,10], label="A")
ax.bar(城市, [10,20,10], bottom=[20,30,10], label="B")hist —— 直方图
参数 | 作用 |
|---|---|
| 几个柱子(或边界数组) |
| 统计范围 |
| 归一化成概率密度 |
| 累计分布 |
|
|
| 多组叠加时必备 |
data = np.random.default_rng(0).normal(0, 1, 1000)
ax.hist(data, bins=30, density=True, histtype="stepfilled", alpha=.7)
ax.hist(data, bins=50, cumulative=True, histtype="step", color="orange")imshow —— 矩阵 / 图片 / 热力图
参数 | 作用 |
|---|---|
| 色表 |
| 颜色对应的值范围 |
|
|
|
|
| 插值方式 |
mat = np.random.default_rng(0).random((10, 10))
im = ax.imshow(mat, cmap="viridis", aspect="auto")
fig.colorbar(im, ax=ax) # 加色标
ax.imshow(img) # 直接显示图片数组
ax.imshow(mat, origin="lower") # 原点改到左下其他图
函数 | 用途 | 关键参数 |
|---|---|---|
| 箱线图 |
|
| 小提琴图 |
|
| 饼图 |
|
| 误差棒 |
|
| 区间填充 |
|
| 等高线 |
|
| 火柴杆图 | 画离散序列 |
| 阶梯图 |
|
| 对数轴 | — |
ax.boxplot([g1, g2, g3], labels=["A","B","C"])
ax.pie([30,50,20], labels=["A","B","C"], autopct="%.1f%%")
ax.errorbar(x, y, yerr=0.2, capsize=3, fmt="o-")
ax.fill_between(x, y-0.2, y+0.2, alpha=.25)
ax.contourf(X, Y, Z, levels=20, cmap="viridis")二、颜色
写法 | 例 |
|---|---|
单字母 |
|
十六进制 |
|
名字 |
|
灰度 |
|
RGB 元组 |
|
色表类别 | 常用值 |
|---|---|
连续(单色渐变) |
|
发散(正负) |
|
分类 |
|
ax.scatter(x, y, c=values, cmap="coolwarm", vmin=-1, vmax=1)
print(plt.colormaps()) # 看有哪些三、坐标轴
方法 | 作用 |
|---|---|
| x 范围 |
| y 范围 |
| 对数轴 |
| 刻度位置 |
| 刻度文字 |
| 刻度样式 |
| 轴标题 |
| 图标题 |
| 翻转 y 轴 |
| 隐藏整个坐标系 |
| 去掉上边框 |
ax.set_xlim(0, 10)
ax.set_ylim(-2, 2)
ax.set_xscale("log")
ax.set_xticks([0, 5, 10])
ax.set_xticklabels(["零", "五", "十"], rotation=45)
ax.tick_params(labelsize=9)
# 去掉上右两条边框(常见美化)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)精细刻度:ticker
from matplotlib.ticker import MultipleLocator, PercentFormatter
ax.xaxis.set_major_locator(MultipleLocator(2)) # 每 2 一个刻度
ax.yaxis.set_major_formatter(PercentFormatter(1.0)) # 0.5 → 50%
ax.xaxis.set_minor_locator(MultipleLocator(0.5)) # 次刻度四、辅助元素
方法 | 作用 |
|---|---|
| 网格 |
| 水平线 |
| 垂直线 |
| 水平色带 |
| 垂直色带 |
| 放一段文字 |
| 带箭头的标注 |
ax.grid(True, alpha=.3, ls="--")
ax.axhline(0, color="gray", lw=.8)
ax.axvline(5, color="gray", lw=.8, ls=":")
ax.axhspan(-1, 1, color="orange", alpha=.1)
ax.text(1, 1, "这里", fontsize=10, color="red")
ax.annotate("最低点", xy=(2, -1), xytext=(4, -1.5),
arrowprops=dict(arrowstyle="->", color="white"))五、图例
参数 | 作用 |
|---|---|
|
|
| 要不要边框 |
| 字号 |
| 几列 |
| 放到图外 |
| 图例标题 |
ax.legend(loc="upper right", frameon=False, fontsize=9)
ax.legend(ncol=2) # 两列
ax.legend(bbox_to_anchor=(1.02, 1), loc="upper left") # 放到图外右侧六、子图
# 规则网格
fig, axes = plt.subplots(2, 2, figsize=(8, 6))
axes[0, 0].plot(x, y)
for ax in axes.flat:
ax.grid(True)
# 共享 x
fig, axes = plt.subplots(2, 1, sharex=True)
# 高度不等
fig, axes = plt.subplots(2, 1, gridspec_kw={"height_ratios": [3, 1]})
# 自由布局
fig, axd = plt.subplot_mosaic([
["左", "右上"],
["左", "右下"],
], figsize=(8, 5))
axd["左"].plot(x, y)
# 大图里嵌小图
ax_in = ax.inset_axes([0.6, 0.6, 0.35, 0.3]) # [x, y, 宽, 高],相对坐标
ax_in.plot(x, y)七、双 y 轴
fig, ax1 = plt.subplots()
ax1.plot(x, y1, color="#58a6ff")
ax1.set_ylabel("左轴", color="#58a6ff")
ax2 = ax1.twinx() # 共享 x,独立 y
ax2.plot(x, y2, color="#f0883e")
ax2.set_ylabel("右轴", color="#f0883e")
fig.tight_layout()八、色标 colorbar
im = ax.imshow(mat, cmap="viridis")
fig.colorbar(im, ax=ax, label="数值")
fig.colorbar(im, ax=ax, orientation="horizontal", shrink=.8)九、样式与全局设置
plt.style.use("ggplot")
print(plt.style.available) # 看全部rcParams | 作用 |
|---|---|
| 默认画布大小 |
| 显示 / 保存分辨率 |
| 全局字号 |
| 字体列表 |
| 负号是否用 Unicode |
| 默认显示网格 |
| 默认是否画上/右边框 |
| 默认线宽 |
plt.rcParams.update({
"figure.figsize": (6, 4),
"figure.dpi": 150,
"savefig.dpi": 200,
"font.size": 10,
"font.sans-serif": ["Microsoft YaHei", "SimHei"],
"axes.unicode_minus": False,
"axes.grid": True,
"axes.spines.top": False,
"axes.spines.right": False,
})十、保存
参数 | 作用 |
|---|---|
| 路径(扩展名决定格式) |
| 分辨率 |
| 裁掉多余白边 |
| 透明背景 |
| 背景色 |
| 边距 |
fig.savefig("a.png", dpi=200, bbox_inches="tight")
fig.savefig("a.png", transparent=True)
fig.savefig("a.svg") # 矢量,放大不糊
fig.savefig("a.pdf")savefig 必须在 show 之前
plt.show() 之后画布被清空,再存是白图。
顺序:画 → tight_layout → savefig → show。
十一、中文显示
plt.rcParams["font.sans-serif"] = ["Microsoft YaHei", "SimHei", "PingFang SC"]
plt.rcParams["axes.unicode_minus"] = False两行都得写
只设字体的话,负号会变成方块——中文字体里的减号不是标准 Unicode 减号。
axes.unicode_minus = False 让它用 ASCII 的 -。
十二、常见坑
现象 | 原因 / 解决 |
|---|---|
中文变方块 | 缺 |
负号变方块 | 缺 |
存出来是空白 |
|
子图标题重叠 |
|
图例挡住数据 | 换 |
日期标签挤成一团 |
|
循环里越画越多 | 每次 |
Jupyter 里不显示 | 开头加 |
图片太糊 | 调大 |
画很多图内存爆 | 每张画完 |
十三、一页速查
画布 plt.subplots(nrows,ncols,figsize,dpi,sharex,sharey,gridspec_kw)
plt.subplot_mosaic([...]) ax.inset_axes([x,y,w,h])
绘制 plot(x,y,color,ls,lw,marker,ms,alpha,label)
scatter(s,c,cmap,edgecolors) bar(width,bottom) barh
hist(bins,density,cumulative,histtype) imshow(cmap,vmin,vmax,aspect,origin)
boxplot violinplot pie(autopct) errorbar(capsize) fill_between
contour contourf step stem semilogy loglog
坐标 set_xlim set_ylim set_xscale set_xticks set_xticklabels tick_params
set_xlabel set_ylabel set_title invert_yaxis axis("off") spines
辅助 grid axhline axvline axhspan axvspan text annotate legend
色 "r" "#58a6ff" "steelblue" (r,g,b) cmap=viridis/coolwarm/tab10 colorbar
样式 plt.style.use plt.rcParams.update({...})
保存 savefig(fname, dpi, bbox_inches="tight", transparent)
双轴 ax2 = ax.twinx()
中文 font.sans-serif + axes.unicode_minus=False