matplotlib›课程›matplotlib 用法大全
matplotlib 用法大全
按功能分类的字典。每个函数列常用参数和一个能跑的例。 两种接口、画布骨架、保存、中文在入门那课。
所有代码假定已有:
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
一、常用图类型
plot —— 折线
| 参数 | 作用 |
|---|
x, y | 数据 |
color / c | 颜色 |
linestyle / ls | 线型 |
linewidth / lw | 线宽 |
marker | 标记符号 |
markersize / ms | 标记大小 |
alpha | 透明度 0~1 |
label | 图例名 |
zorder | 图层顺序(大的在上) |
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 —— 散点
| 参数 | 作用 |
|---|
s | 点大小(面积) |
c | 颜色(可以是数组,配合 cmap) |
cmap | 色表名 |
marker | 形状 |
edgecolors | 描边颜色 |
linewidths | 描边宽度 |
vmin / vmax | 色标范围 |
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 —— 柱状
| 参数 | 作用 |
|---|
x, height | 位置、高度 |
width | 柱子宽度(默认 0.8) |
bottom | 堆叠时的底部 |
align | "center" / "edge" |
color | 可以是颜色列表 |
城市 = ["北京", "上海", "广州"]
销量 = [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 —— 直方图
| 参数 | 作用 |
|---|
bins | 几个柱子(或边界数组) |
range | 统计范围 |
density | 归一化成概率密度 |
cumulative | 累计分布 |
histtype | "bar" / "step" / "stepfilled" |
alpha | 多组叠加时必备 |
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 —— 矩阵 / 图片 / 热力图
| 参数 | 作用 |
|---|
cmap | 色表 |
vmin / vmax | 颜色对应的值范围 |
aspect | "auto" / "equal" |
origin | "upper"(默认,原点在左上)/ "lower" |
interpolation | 插值方式 |
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") # 原点改到左下
其他图
| 函数 | 用途 | 关键参数 |
|---|
boxplot(data) | 箱线图 | labels、vert=False |
violinplot(data) | 小提琴图 | showmeans=True |
pie(sizes) | 饼图 | labels、autopct="%.1f%%"、explode |
errorbar(x,y,yerr) | 误差棒 | capsize、fmt |
fill_between(x,y1,y2) | 区间填充 | alpha、where |
contour / contourf | 等高线 | levels、cmap |
stem(x,y) | 火柴杆图 | 画离散序列 |
step(x,y) | 阶梯图 | where="mid" |
semilogy() / loglog() | 对数轴 | — |
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")
二、颜色
| 写法 | 例 |
|---|
| 单字母 | r g b c m y k w |
| 十六进制 | "#58a6ff" |
| 名字 | "steelblue"、"tomato" |
| 灰度 | "0.5"(0 黑,1 白) |
| RGB 元组 | (0.2, 0.4, 0.8),0~1 |
| 色表类别 | 常用值 |
|---|
| 连续(单色渐变) | viridis(默认)、plasma、Blues、Reds |
| 发散(正负) | coolwarm、RdBu、bwr |
| 分类 | tab10、Set2、Paired |
ax.scatter(x, y, c=values, cmap="coolwarm", vmin=-1, vmax=1)
print(plt.colormaps()) # 看有哪些
三、坐标轴
| 方法 | 作用 |
|---|
set_xlim(a, b) | x 范围 |
set_ylim(a, b) | y 范围 |
set_xscale("log") | 对数轴 |
set_xticks(list) | 刻度位置 |
set_xticklabels(list) | 刻度文字 |
tick_params(labelsize, rotation) | 刻度样式 |
set_xlabel(s, fontsize) | 轴标题 |
set_title(s, fontsize, pad) | 图标题 |
invert_yaxis() | 翻转 y 轴 |
axis("off") | 隐藏整个坐标系 |
spines["top"].set_visible(False) | 去掉上边框 |
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)) # 次刻度
四、辅助元素
| 方法 | 作用 |
|---|
grid(True, alpha, ls) | 网格 |
axhline(y) | 水平线 |
axvline(x) | 垂直线 |
axhspan(y1, y2) | 水平色带 |
axvspan(x1, x2) | 垂直色带 |
text(x, y, s) | 放一段文字 |
annotate(s, xy, xytext) | 带箭头的标注 |
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"))
五、图例
| 参数 | 作用 |
|---|
loc | "best"(默认)/ "upper right" / "lower left" … |
frameon | 要不要边框 |
fontsize | 字号 |
ncol | 几列 |
bbox_to_anchor | 放到图外 |
title | 图例标题 |
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 | 作用 |
|---|
figure.figsize | 默认画布大小 |
figure.dpi / savefig.dpi | 显示 / 保存分辨率 |
font.size | 全局字号 |
font.sans-serif | 字体列表 |
axes.unicode_minus | 负号是否用 Unicode |
axes.grid | 默认显示网格 |
axes.spines.top / right | 默认是否画上/右边框 |
lines.linewidth | 默认线宽 |
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,
})
十、保存
| 参数 | 作用 |
|---|
fname | 路径(扩展名决定格式) |
dpi | 分辨率 |
bbox_inches="tight" | 裁掉多余白边 |
transparent | 透明背景 |
facecolor | 背景色 |
pad_inches | 边距 |
fig.savefig("a.png", dpi=200, bbox_inches="tight")
fig.savefig("a.png", transparent=True)
fig.savefig("a.svg") # 矢量,放大不糊
fig.savefig("a.pdf")
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 的 -。
十二、常见坑
| 现象 | 原因 / 解决 |
|---|
| 中文变方块 | 缺 font.sans-serif |
| 负号变方块 | 缺 axes.unicode_minus=False |
| 存出来是空白 | savefig 放在了 show 之后 |
| 子图标题重叠 | fig.tight_layout() 或 constrained_layout=True |
| 图例挡住数据 | 换 loc,或 bbox_to_anchor 挪出去 |
| 日期标签挤成一团 | fig.autofmt_xdate() 或 rotation=45 |
| 循环里越画越多 | 每次 subplots() 新建,用完 plt.close(fig) |
| Jupyter 里不显示 | 开头加 %matplotlib inline |
| 图片太糊 | 调大 dpi |
| 画很多图内存爆 | 每张画完 plt.close(fig) |
十三、一页速查
画布 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