Matplotlib入门教程(十八):参考文档——接口索引与快速查阅手册

一、两大编程接口

Matplotlib 提供了两种使用方式,适用于不同场景。

特性 Axes 接口(显式/面向对象) pyplot 接口(隐式/函数式)
使用方式 先创建 Figure 和 Axes 对象,再调用对象方法 直接调用 pyplot 模块函数,隐式操作当前图表
适用场景 复杂图表、多子图、需要精细控制 快速绘图、交互式探索、简单图表
代码示例 fig, ax = plt.subplots(); ax.plot(x, y) plt.plot(x, y); plt.title("标题")
推荐程度 推荐(更清晰、更可控) 适合简单场景和快速原型

Axes 接口是官方推荐的编程方式,代码逻辑更清晰,在处理多子图和复杂图表时不易出错。

二、常用函数索引

按主题归类的函数入口,便于快速定位。

函数 相关内容
plot() 折线图
scatter() 散点图
bar() / barh() 柱状图、水平柱状图、数值标签、分组柱状图
hist() 直方图
pie() 饼图、饼图标签
imshow() 图像/热力图
subplots() 创建子图网格
figure() 创建画布
savefig() 保存图表
errorbar() 带误差棒折线图
boxplot() 箱线图
contour() / contourf() 等高线、填充等高线、标签
fill_between() / fill_betweenx() 填充区域
legend() 图例
text() / annotate() 文本、带箭头标注
title() / xlabel() / ylabel() 标题与轴标签
colorbar() 颜色条
subplot_mosaic() 复杂非均匀布局

管理类函数:

函数 相关内容
Figure 与 Axes 管理 axes()、cla()、clf()、close()、delaxes()、gca()、gcf()、sca()、subplot()、subplot2grid()、twinx()、twiny()
高级绘图 step()、stem()、eventplot()、stackplot()、broken_barh()、vlines()、hlines()、fill()、loglog()、semilogx()、semilogy()
跨度线与矢量场 axhline()、axhspan()、axvline()、axvspan()、axline()、quiver()、quiverkey()、barbs()、streamplot()
频谱分析 acorr()、xcorr()、psd()、csd()、specgram()、cohere()、angle_spectrum()、magnitude_spectrum()、phase_spectrum()
二维数据与统计图 hist2d()、hexbin()、stairs()、matshow()、pcolor()、pcolormesh()、spy()、figimage()、ecdf()、violinplot()
三角网格与极坐标 triplot()、tripcolor()、tricontour()、tricontourf()、polar()、rgrids()、thetagrids()
坐标轴配置 xlim()、ylim()、xscale()、yscale()、xticks()、yticks()、tick_params()、grid()、axis()、box()、autoscale()
布局与配置 subplots_adjust()、tight_layout()、margins()、rc()、rc_context()、rcdefaults()、clim()、get_cmap()、set_cmap()、imread()、imsave()、show()、ion()、ioff()
工具与交互 connect()、disconnect()、ginput()、waitforbuttonpress()、findobj()、setp()、xkcd()
三、pyplot 模块 ------ 全部函数列表

pyplot 是 Matplotlib 的顶层接口,提供类似 MATLAB 的绘图体验。

1. Figure 与 Axes 管理
函数 功能说明
figure() 创建新的 Figure 或激活已有 Figure
subplots() 推荐 创建 Figure 和一组 Axes 子图
subplot() 添加单个子图到当前 Figure
subplot2grid() 在网格布局的指定位置创建子图
subplot_mosaic() 使用标签字符串创建复杂非均匀布局
axes() 在当前 Figure 中添加一个 Axes
gca() 获取当前 Axes 对象
gcf() 获取当前 Figure 对象
sca() 设置当前 Axes
cla() 清除当前 Axes
clf() 清除当前 Figure
close() 关闭 Figure 窗口
delaxes() 从 Figure 中移除指定的 Axes
fignum_exists() 检查指定编号的 Figure 是否存在
get_figlabels() 返回所有 Figure 的标签列表
get_fignums() 返回所有 Figure 的编号列表
twinx() 创建共享 x 轴的双 y 轴
twiny() 创建共享 y 轴的双 x 轴
2. 基本绘图
函数 功能说明
plot() 绘制折线图(最常用)
scatter() 绘制散点图,支持大小/颜色/透明度映射
bar() 绘制垂直柱状图
barh() 绘制水平柱状图
bar_label() 在柱状图的柱子上添加数值标签
grouped_bar() 绘制分组柱状图
pie() 绘制饼图
pie_label() 在饼图上添加标签
stem() 绘制茎叶图(火柴杆图)
eventplot() 绘制事件图
step() 绘制阶梯图
fill() 绘制填充多边形
fill_between() 填充两条水平曲线之间的区域
fill_betweenx() 填充两条垂直曲线之间的区域
stackplot() 绘制堆叠面积图
broken_barh() 绘制水平断条图(甘特图风格)
vlines() / hlines() 绘制垂直/水平参考线
errorbar() 绘制带误差棒的折线图
loglog() 双对数坐标折线图
semilogx() / semilogy() 单轴对数坐标折线图
polar() 在极坐标系中绘图
3. 跨度线(Spans)
函数 功能说明
axhline() 添加横跨 Axes 的水平线
axhspan() 添加横跨 Axes 的水平着色带
axvline() 添加纵跨 Axes 的垂直线
axvspan() 添加纵跨 Axes 的垂直着色带
axline() 添加通过两点的无限长直线
4. 频谱分析
函数 功能说明
acorr() 绘制自相关图
xcorr() 绘制互相关图
angle_spectrum() 绘制角度频谱
magnitude_spectrum() 绘制幅度频谱
phase_spectrum() 绘制相位频谱
psd() 绘制功率谱密度
csd() 绘制互谱密度
cohere() 绘制相干性
specgram() 绘制频谱图(时频图)
5. 统计图
函数 功能说明
boxplot() 绘制箱线图
violinplot() 绘制小提琴图
ecdf() 绘制经验累积分布函数(ECDF)
6. 分箱与直方图
函数 功能说明
hist() 绘制一维直方图
hist2d() 绘制二维直方图
hexbin() 绘制六边形分箱图
stairs() 绘制阶梯直方图
7. 等高线
函数 功能说明
contour() 绘制等高线
contourf() 绘制填充等高线
clabel() 给等高线添加标签
8. 二维数组与图像
函数 功能说明
imshow() 显示图像或二维数组(热力图)
matshow() 将矩阵显示为新 Figure 中的图像
pcolor() 绘制伪彩色网格图(PolyCollection)
pcolormesh() 绘制伪彩色网格图(QuadMesh,性能更好)
spy() 绘制稀疏矩阵的非零元素图案
figimage() 在 Figure 级别放置图像
9. 非结构化三角网格
函数 功能说明
triplot() 绘制非结构化三角网格
tripcolor() 绘制三角网格伪彩色图
tricontour() / tricontourf() 三角网格等高线/填充等高线
10. 文本与标注
函数 功能说明
text() 在 Axes 指定坐标添加文本
figtext() 在 Figure 指定位置添加文本
annotate() 添加带箭头的标注
arrow() 添加箭头
legend() 在 Axes 中添加图例
figlegend() 在 Figure 级别添加图例
table() 在 Axes 中添加表格
11. 矢量场
函数 功能说明
quiver() 绘制矢量场(箭头图)
quiverkey() 给矢量场添加图例标尺
barbs() 绘制风羽图
streamplot() 绘制流线图
12. 坐标轴配置
函数 功能说明
title() / suptitle() 设置 Axes 标题 / Figure 总标题
xlabel() / ylabel() 设置 x/y 轴标签
xlim() / ylim() 获取或设置 x/y 轴范围
xscale() / yscale() 设置轴比例(linear/log/symlog/logit)
xticks() / yticks() 获取或设置刻度位置和标签
tick_params() 调整刻度外观
ticklabel_format() 设置刻度标签格式
locator_params() 控制刻度定位器的参数
minorticks_on() / minorticks_off() 显示/隐藏次要刻度
rgrids() / thetagrids() 极坐标网格线
grid() 开启或关闭网格线
axis() 获取或设置轴属性的便捷函数
box() 开启或关闭 Axes 的边框线
autoscale() 自动缩放坐标轴以适应数据
13. 布局
函数 功能说明
subplots_adjust() 手动调整子图间距
tight_layout() 自动调整子图参数使之紧凑排列
margins() 设置或获取坐标轴的数据边距
subplot_tool() 启动交互式子图调整工具窗口
14. 颜色映射
函数 功能说明
colorbar() 添加颜色条
clim() 设置颜色映射的数据范围
get_cmap() 获取指定名称的 colormap 对象
set_cmap() 设置默认 colormap
gci() / sci() 获取/设置当前可映射颜色的图像对象
imread() 从文件读取图像到数组
imsave() 将数组保存为图像文件
colormaps / color_sequences colormap / 颜色序列注册表对象
15. 配置
函数 功能说明
rc() 设置 rc 参数(可批量设置)
rc_context() 临时设置 rc 参数的上下文管理器
rcdefaults() 恢复所有 rc 参数为默认值
16. 输出与交互
函数 功能说明
show() 显示所有打开的 Figure
savefig() 保存当前 Figure 到文件
draw() 强制重新渲染当前 Figure
draw_if_interactive() 如果在交互模式则渲染 Figure
pause() 暂停指定的秒数
ion() / ioff() 开启/关闭交互模式
isinteractive() 返回当前是否处于交互模式
install_repl_displayhook() / uninstall_repl_displayhook() 安装/卸载 REPL 显示钩子
switch_backend() 切换后端
17. 其他工具函数
函数 功能说明
connect() / disconnect() 绑定/解绑事件回调函数
ginput() 通过鼠标点击获取坐标点
waitforbuttonpress() 等待鼠标或键盘按下
findobj() 查找匹配条件的 Artist 对象
get() / getp() 获取 Artist 对象的属性值
setp() 设置 Artist 对象的属性
get_current_fig_manager() 获取当前 Figure 的窗口管理器
new_figure_manager() 为指定 Figure 创建新的 Figure 管理器
set_loglevel() 设置 Matplotlib 日志级别
xkcd() 切换为 xkcd(手绘漫画)风格
四、Axes 对象 ------ 核心方法列表

Axes 代表 Figure 中的一个子图,包含数据、刻度、标签、标题等。

1. 基本绘图方法
方法 功能说明
Axes.plot() 折线图
Axes.scatter() 散点图
Axes.bar() / Axes.barh() 垂直/水平柱状图
Axes.bar_label() 在柱子上添加数值标签
Axes.pie() 饼图
Axes.stem() 茎叶图
Axes.eventplot() 事件图
Axes.step() 阶梯图
Axes.fill() 填充多边形
Axes.fill_between() / fill_betweenx() 水平/垂直填充区域
Axes.stackplot() 堆叠面积图
Axes.broken_barh() 水平断条图
Axes.vlines() / hlines() 垂直/水平参考线
Axes.errorbar() 带误差棒折线图
Axes.loglog() 双对数坐标
Axes.semilogx() / semilogy() 单轴对数坐标
2. 跨度线方法
方法 功能说明
Axes.axhline() 水平参考线
Axes.axvline() 垂直参考线
Axes.axhspan() 水平着色带
Axes.axvspan() 垂直着色带
Axes.axline() 通过两点的无限长直线
3. 频谱分析方法
方法 功能说明
Axes.acorr() / xcorr() 自相关/互相关图
Axes.angle_spectrum() 角度频谱
Axes.magnitude_spectrum() 幅度频谱
Axes.phase_spectrum() 相位频谱
Axes.psd() / csd() 功率谱密度 / 互谱密度
Axes.cohere() 相干性
Axes.specgram() 频谱图(时频图)
4. 统计方法
方法 功能说明
Axes.boxplot() 箱线图
Axes.bxp() 从预先计算的统计数据绘制箱线图
Axes.violinplot() 小提琴图
Axes.violin() 从预先计算的统计数据绘制小提琴图
Axes.ecdf() 经验累积分布函数
5. 分箱与直方图方法
方法 功能说明
Axes.hist() 直方图
Axes.hist2d() 二维直方图
Axes.hexbin() 六边形分箱图
Axes.stairs() 阶梯直方图
6. 等高线方法
方法 功能说明
Axes.contour() 等高线
Axes.contourf() 填充等高线
Axes.clabel() 等高线标签
7. 二维数组方法
方法 功能说明
Axes.imshow() 显示图像/热力图
Axes.matshow() 矩阵图像
Axes.pcolor() 伪彩色网格(PolyCollection)
Axes.pcolorfast() 快速伪彩色(使用 imshow 绘制)
Axes.pcolormesh() 伪彩色网格(QuadMesh,推荐)
Axes.spy() 稀疏矩阵图案
8. 非结构化三角网格方法
方法 功能说明
Axes.triplot() 三角网格线
Axes.tripcolor() 三角网格伪彩色
Axes.tricontour() / tricontourf() 三角网格等高线/填充等高线
9. 文本与标注方法
方法 功能说明
Axes.text() 添加文本
Axes.annotate() 添加带箭头的标注
Axes.table() 添加表格
Axes.arrow() 添加箭头
Axes.inset_axes() 在 Axes 内创建嵌入子图
Axes.indicate_inset() / indicate_inset_zoom() 标记嵌入子图区域/放大区域
Axes.secondary_xaxis() / secondary_yaxis() 添加辅助坐标轴
10. 矢量场方法
方法 功能说明
Axes.quiver() 矢量场(箭头图)
Axes.quiverkey() 矢量场图例标尺
Axes.barbs() 风羽图
Axes.streamplot() 流线图
11. 清除与外观方法
方法 功能说明
Axes.cla() / clear() 清除 Axes 中的所有内容
Axes.axis() 设置轴可见性或范围
Axes.set_axis_off() / set_axis_on() 隐藏/显示坐标轴
Axes.set_frame_on() / get_frame_on() 显示/获取 Axes 边框
Axes.set_axisbelow() / get_axisbelow() 设置/获取网格/刻度层级
Axes.grid() 设置网格线
Axes.get_facecolor() / set_facecolor() 获取/设置 Axes 背景色
Axes.set_prop_cycle() 设置线条颜色/线型等属性的循环
12. 坐标轴与刻度控制

坐标轴访问:

方法 功能说明
Axes.xaxis / Axes.yaxis 获取 x/y 轴的 Axis 对象(属性)
Axes.get_xaxis() / get_yaxis() 获取 x/y 轴的 Axis 对象

坐标轴范围与方向:

方法 功能说明
Axes.set_xlim() / get_xlim() 设置/获取 x 轴范围
Axes.set_ylim() / get_ylim() 设置/获取 y 轴范围
Axes.set_xbound() / get_xbound() 设置/获取 x 轴下界和上界
Axes.invert_xaxis() / invert_yaxis() 反转轴方向
Axes.xaxis_inverted() / yaxis_inverted() 查询轴是否反转
Axes.update_datalim() 用新数据点扩展数据范围

坐标轴标签与图例:

方法 功能说明
Axes.set_xlabel() / get_xlabel() 设置/获取 x 轴标签
Axes.set_ylabel() / get_ylabel() 设置/获取 y 轴标签
Axes.label_outer() 仅保留最外侧子图的刻度标签
Axes.set_title() / get_title() 设置/获取 Axes 标题
Axes.legend() 添加图例
Axes.get_legend() 获取当前图例对象
Axes.get_legend_handles_labels() 获取图例的句柄和标签

坐标轴比例与自动缩放:

方法 功能说明
Axes.set_xscale() / get_xscale() 设置/获取 x 轴比例
Axes.set_yscale() / get_yscale() 设置/获取 y 轴比例
Axes.autoscale() 自动缩放视图以适应数据
Axes.autoscale_view() 仅自动缩放视图
Axes.margins() 设置或获取数据边距
Axes.relim() 根据当前 Artist 重新计算数据范围
Axes.set_xmargin() / get_xmargin() 设置/获取 x 轴边距
Axes.set_autoscale_on() / get_autoscale_on() 设置/获取是否自动缩放

宽高比:

方法 功能说明
Axes.set_aspect() / get_aspect() 设置/获取坐标轴宽高比
Axes.set_box_aspect() / get_box_aspect() 设置/获取 Axes 盒子宽高比
Axes.apply_aspect() 应用当前宽高比设置
Axes.set_adjustable() / get_adjustable() 设置/获取可调整的方向

刻度和刻度标签:

方法 功能说明
Axes.set_xticks() / get_xticks() 设置/获取 x 轴刻度位置
Axes.set_yticks() / get_yticks() 设置/获取 y 轴刻度位置
Axes.set_xticklabels() / get_xticklabels() 设置/获取 x 轴刻度标签
Axes.set_yticklabels() / get_yticklabels() 设置/获取 y 轴刻度标签
Axes.get_xmajorticklabels() / get_xminorticklabels() 获取 x 轴主/次刻度标签
Axes.get_xgridlines() / get_ygridlines() 获取 x/y 轴网格线
Axes.xaxis_date() / yaxis_date() 将轴刻度设置为日期格式
Axes.minorticks_on() / minorticks_off() 显示/隐藏次要刻度
Axes.ticklabel_format() 设置刻度标签格式
Axes.tick_params() 调整刻度外观参数
Axes.locator_params() 控制刻度定位器参数
13. 双轴与共享轴
方法 功能说明
Axes.twinx() 创建共享 x 轴的双 y 轴
Axes.twiny() 创建共享 y 轴的双 x 轴
Axes.sharex() / sharey() 与其他 Axes 共享 x/y 轴
Axes.get_shared_x_axes() / get_shared_y_axes() 获取共享轴的 Grouper 对象
14. Axes 位置
方法 功能说明
Axes.get_position() / set_position() 获取/设置 Axes 在 Figure 中的位置和大小
Axes.get_anchor() / set_anchor() 获取/设置 Axes 的锚点
Axes.get_axes_locator() / set_axes_locator() 获取/设置 Axes 定位器回调函数
Axes.get_subplotspec() / set_subplotspec() 获取/设置 SubplotSpec 对象
Axes.reset_position() 重置 Axes 位置为原始值
15. 子元素查询与绘制
方法 功能说明
Axes.get_children() 获取所有子 Artist
Axes.get_images() 获取所有图像对象
Axes.get_lines() 获取所有折线对象
Axes.findobj() 查找匹配条件的子 Artist
Axes.draw() 渲染 Axes
Axes.get_window_extent() 获取 Axes 在显示窗口中的边界
Axes.get_tightbbox() 获取 Axes 的紧凑边界框
16. 其他方法
方法 功能说明
Axes.set() 批量设置属性
Axes.get_figure() 获取所属的 Figure 对象
Axes.remove() 从 Figure 中移除自身
Axes.has_data() 检查是否有数据
Axes.viewLim / Axes.dataLim 视图范围 / 数据范围(属性)
Axes.spines 边框线字典(属性)
五、Figure 对象 ------ 核心方法列表

Figure 是整个图表的顶层容器,管理所有的 Axes、Artist 和布局。

1. 添加 Axes 和 SubFigure
方法 功能说明
Figure.subplots() 推荐 创建 Axes 子图网格
Figure.add_subplot() 按行列位置添加单个子图
Figure.add_axes() 在指定位置和大小添加 Axes
Figure.subplot_mosaic() 使用标签布局创建复杂子图排列
Figure.add_gridspec() 添加 GridSpec 布局对象
Figure.subfigures() / add_subfigure() 创建嵌套子 Figure
Figure.get_axes() 获取所有 Axes
Figure.delaxes() 移除指定的 Axes
2. 保存与标注
方法 功能说明
Figure.savefig() 保存 Figure 到文件
Figure.suptitle() / get_suptitle() 设置/获取 Figure 总标题
Figure.supxlabel() / supylabel() 设置 Figure 级别 x/y 标签
Figure.colorbar() 添加颜色条
Figure.legend() 添加全局图例
Figure.text() 在 Figure 级别添加文本
Figure.align_labels() 对齐所有子图的轴标签
Figure.align_xlabels() / align_ylabels() 对齐 x/y 轴标签
Figure.align_titles() 对齐所有子图的标题
Figure.autofmt_xdate() 自动旋转日期刻度标签
3. Figure 几何与布局
方法 功能说明
Figure.set_size_inches() / get_size_inches() 设置/获取 Figure 尺寸(英寸)
Figure.set_figheight() / get_figheight() 设置/获取 Figure 高度
Figure.set_figwidth() / get_figwidth() 设置/获取 Figure 宽度
Figure.set_dpi() / get_dpi() 设置/获取 DPI
Figure.subplots_adjust() 手动调整子图间距
Figure.set_layout_engine() 设置布局引擎('constrained'/'compressed'/'none')
Figure.get_layout_engine() 获取当前布局引擎
4. 状态管理与外观
方法 功能说明
Figure.clear() 清除 Figure
Figure.gca() / sca() 获取/设置当前 Axes
Figure.show() / draw() 显示/渲染 Figure
Figure.get_tightbbox() 获取 Figure 的紧凑边界框
Figure.set_facecolor() / get_facecolor() 设置/获取 Figure 背景色
Figure.set_edgecolor() / get_edgecolor() 设置/获取 Figure 边框颜色
Figure.add_artist() 添加任意 Artist
Figure.figimage() 在 Figure 级别放置图像
Figure.get_children() 获取所有子 Artist
六、SubFigure 对象 ------ 方法列表

SubFigure 是嵌套在父 Figure 内的逻辑子 Figure,拥有与 Figure 类似的方法。

分类 方法
添加 Axes subplots()、add_subplot()、add_axes()、subplot_mosaic()、add_gridspec()、subfigures()、add_subfigure()、delaxes()
标注 suptitle()、supxlabel()、supylabel()、colorbar()、legend()、text()、align_labels()、align_xlabels()、align_ylabels()、align_titles()
Artist 与外观 add_artist()、get_children()、set_frameon()、set_linewidth()、set_facecolor()、set_edgecolor()、set_dpi()
七、样式配置速查
1. 内置样式表

通过 plt.style.use('name') 切换样式。

样式名称 风格描述
default 默认样式,清晰中性
ggplot 模拟 R ggplot2 风格,灰色背景加白色网格
seaborn-v0_8 类似 seaborn 库的现代化风格
seaborn-v0_8-bright seaborn 亮色调
seaborn-v0_8-colorblind seaborn 色盲友好色调
seaborn-v0_8-dark seaborn 深色风格
seaborn-v0_8-darkgrid seaborn 深色带网格
seaborn-v0_8-muted seaborn 柔色调
seaborn-v0_8-notebook seaborn notebook 风格
seaborn-v0_8-paper seaborn 论文风格
seaborn-v0_8-pastel seaborn 粉色调
seaborn-v0_8-poster seaborn 海报风格
seaborn-v0_8-talk seaborn 演讲风格
seaborn-v0_8-ticks seaborn 刻度风格
seaborn-v0_8-white seaborn 白色背景
seaborn-v0_8-whitegrid seaborn 白色带网格
fivethirtyeight 模仿 FiveThirtyEight 数据新闻风格
dark_background 深色背景,适合演示和夜间使用
bmh Bayesian Methods for Hackers 风格
grayscale 灰度风格,适合黑白打印
classic Matplotlib v1.x 经典风格
fast 简化样式,渲染速度更快
Solarize_Light2 Solarized 浅色主题
tableau-colorblind10 Tableau 色盲友好调色板
2. 常用 rcParams 配置
参数 说明 示例值
figure.figsize 默认图表尺寸(英寸) [8, 6]
figure.dpi 默认分辨率 100
figure.facecolor Figure 背景色 'white'
font.size 全局字体大小 12
font.family 字体族 'sans-serif'
font.sans-serif 无衬线字体列表 ['DejaVu Sans', ...]
axes.titlesize 标题字体大小 'large'
axes.labelsize 轴标签字体大小 'medium'
axes.grid 默认是否显示网格 False
axes.facecolor Axes 背景色 'white'
lines.linewidth 默认线宽 1.5
lines.markersize 默认标记大小 6
legend.loc 图例默认位置 'best'
xtick.labelsize x 轴刻度标签大小 'medium'
savefig.dpi 保存图片的默认分辨率 'figure'
image.cmap 默认 colormap 'viridis'
3. colormap(颜色映射)速查
分类 colormap 名称 适用场景
感知均匀(Sequential) viridis, plasma, inferno, magma, cividis 连续数据,色盲友好,推荐首选
顺序(单色渐变) Greys, Purples, Blues, Greens, Oranges, Reds, YlOrBr, YlOrRd, OrRd, PuRd, RdPu, BuPu, GnBu, PuBu, YlGnBu, PuBuGn, BuGn, YlGn 从低到高的连续数据,单色调
发散(Diverging) PiYG, PRGn, BrBG, PuOr, RdGy, RdBu, RdYlBu, RdYlGn, Spectral, coolwarm, bwr, seismic 有中心参考点的双向数据
循环(Cyclic) twilight, twilight_shifted, hsv 周期性数据(如角度、时间)
定性(Qualitative) Pastel1, Pastel2, Paired, Accent, Dark2, Set1, Set2, Set3, tab10, tab20, tab20b, tab20c 离散分类数据
杂项 flag, prism, ocean, gist_earth, terrain, gnuplot, cubehelix, brg, rainbow, jet, turbo, nipy_spectral, gist_ncar 特殊用途或视觉效果

重要提示: 'viridis' 是 Matplotlib 2.0 以来的默认 colormap,具有优秀的感知均匀性和色盲友好特性,是大多数场景的首选。避免使用 'jet' 和 'rainbow',它们存在感知失真问题。

八、常用示例
示例 1:基本折线图与散点图

python

复制代码
import matplotlib.pyplot as plt
import numpy as np

# 生成数据
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# 创建 Figure 和 Axes(显式接口,推荐)
fig, ax = plt.subplots(figsize=(8, 4), layout='constrained')

# 绘制两条折线
ax.plot(x, y1, label='sin(x)', color='blue', linewidth=2)
ax.plot(x, y2, label='cos(x)', color='red', linestyle='--', linewidth=2)

# 在峰值位置添加高亮散点
peak_idx_sin = np.argmax(y1)
peak_idx_cos = np.argmax(y2)
ax.scatter(x[peak_idx_sin], y1[peak_idx_sin], color='blue', s=100, zorder=5)
ax.scatter(x[peak_idx_cos], y2[peak_idx_cos], color='red', s=100, zorder=5)

# 装饰
ax.set_title('Sine and Cosine Functions', fontsize=14)
ax.set_xlabel('x (radians)')
ax.set_ylabel('Amplitude')
ax.legend(loc='upper right')
ax.grid(True, alpha=0.3)

plt.show()
示例 2:多子图布局(2×2)

python

复制代码
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2 * np.pi, 100)

# 创建 2x2 子图(面向对象接口)
fig, axes = plt.subplots(2, 2, figsize=(10, 8), layout='constrained')
fig.suptitle('Multi-panel RUNOOB Demo', fontsize=16)

# 子图 (0,0):折线图
axes[0, 0].plot(x, np.sin(x), color='tab:blue', linewidth=2)
axes[0, 0].set_title('Line Plot')
axes[0, 0].set_ylabel('sin(x)')

# 子图 (0,1):散点图
np.random.seed(42)
colors = np.random.rand(50)
sizes = np.random.rand(50) * 200
axes[0, 1].scatter(np.random.rand(50), np.random.rand(50),
                   c=colors, s=sizes, alpha=0.6, cmap='viridis')
axes[0, 1].set_title('Scatter Plot')

# 子图 (1,0):柱状图(带数值标签)
categories = ['A', 'B', 'C', 'D', 'E']
values = [23, 45, 56, 78, 32]
bars = axes[1, 0].bar(categories, values, color='tab:green', edgecolor='white')
axes[1, 0].bar_label(bars)
axes[1, 0].set_title('Bar Chart')

# 子图 (1,1):直方图
data = np.random.randn(1000)
axes[1, 1].hist(data, bins=30, color='tab:orange', edgecolor='white', alpha=0.8)
axes[1, 1].axvline(x=0, color='red', linestyle='--', linewidth=2)
axes[1, 1].set_title('Histogram')

plt.show()
示例 3:热力图与等高线对比

python

复制代码
import matplotlib.pyplot as plt
import numpy as np

# 创建二维网格数据
x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) * np.cos(Y)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5), layout='constrained')

# 左图:热力图(imshow)
im = ax1.imshow(Z, extent=[-3, 3, -3, 3], origin='lower',
                cmap='viridis', aspect='auto')
ax1.set_title('Heatmap (imshow)', fontsize=14)
ax1.set_xlabel('X')
ax1.set_ylabel('Y')
fig.colorbar(im, ax=ax1, label='Amplitude', shrink=0.8)

# 右图:填充等高线(contourf)
contour = ax2.contourf(X, Y, Z, levels=15, cmap='RdYlBu')
ax2.contour(X, Y, Z, levels=15, colors='black', linewidths=0.5)
ax2.set_title('Filled Contour (contourf)', fontsize=14)
ax2.set_xlabel('X')
ax2.set_ylabel('Y')
fig.colorbar(contour, ax=ax2, label='Amplitude', shrink=0.8)

plt.show()
示例 4:样式切换与保存图片

python

复制代码
import matplotlib.pyplot as plt
import numpy as np

# 使用 ggplot 样式,再微调部分参数
plt.style.use('ggplot')
plt.rcParams['figure.figsize'] = [8, 6]
plt.rcParams['font.size'] = 12

x = np.linspace(0, 10, 50)
y1 = np.exp(-x / 3) * np.sin(2 * x)
y2 = np.exp(-x / 3) * np.cos(2 * x)

fig, ax = plt.subplots()
ax.plot(x, y1, 'o-', label='Damped sin', markersize=6)
ax.plot(x, y2, 's--', label='Damped cos', markersize=6)

# 标注第一个峰值
peak_idx = np.argmax(y1)
ax.annotate(f'Peak: {y1[peak_idx]:.2f}',
            xy=(x[peak_idx], y1[peak_idx]),
            xytext=(x[peak_idx] + 1.5, y1[peak_idx] + 0.15),
            arrowprops=dict(arrowstyle='->', color='gray'),
            fontsize=10)

ax.set_title('Damped Oscillation', fontsize=16)
ax.set_xlabel('Time (s)')
ax.set_ylabel('Amplitude')
ax.legend()
ax.grid(True)

# 保存为 300 DPI 高质量 PNG
fig.savefig('runoob_damped_oscillation.png', dpi=300, bbox_inches='tight')
print("runoob: figure saved successfully")

plt.show()
示例 5:mosaic 复杂布局

python

复制代码
import matplotlib.pyplot as plt
import numpy as np

# mosaic 字符串定义布局
layout = """
A A A
B C D
"""

fig, axes = plt.subplot_mosaic(layout, figsize=(10, 6), layout='constrained')
fig.suptitle('Complex Mosaic Layout (RUNOOB)', fontsize=16)

# 面板 A:折线图(横跨顶部)
x = np.linspace(0, 10, 100)
axes['A'].plot(x, np.sin(x), label='sin(x)')
axes['A'].plot(x, np.cos(x), label='cos(x)')
axes['A'].set_title('Panel A: Line Plot')
axes['A'].legend()

# 面板 B:饼图
sizes = [30, 25, 20, 15, 10]
labels = ['Python', 'Java', 'C++', 'Rust', 'Go']
axes['B'].pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90)
axes['B'].set_title('Panel B: Pie Chart')

# 面板 C:柱状图
axes['C'].bar(['X', 'Y', 'Z'], [10, 25, 15],
              color=['#ff6b6b', '#4ecdc4', '#45b7d1'])
axes['C'].set_title('Panel C: Bar Chart')

# 面板 D:热力图
matrix = np.random.rand(5, 5)
im = axes['D'].imshow(matrix, cmap='Blues', aspect='auto')
axes['D'].set_title('Panel D: Heatmap')
fig.colorbar(im, ax=axes['D'])

plt.show()
示例 6:双 y 轴与嵌入子图

python

复制代码
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(8, 5), layout='constrained')

x = np.linspace(0, 10, 100)

# 主图
ax.plot(x, np.sin(x), 'b-', label='sin(x) [amplitude]')
ax.set_xlabel('x (radians)')
ax.set_ylabel('sin(x)', color='blue')
ax.tick_params(axis='y', labelcolor='blue')

# 创建双 y 轴(共享 x 轴)
ax2 = ax.twinx()
ax2.plot(x, np.exp(x / 5), 'r--', label='exp(x/5) [growth]')
ax2.set_ylabel('exp(x/5)', color='red')
ax2.tick_params(axis='y', labelcolor='red')

# 在 ax 中添加嵌入子图(放大局部区域)
axins = ax.inset_axes([0.15, 0.5, 0.3, 0.35])
axins.plot(x, np.sin(x), 'b-')
axins.set_xlim(3, 5)
axins.set_ylim(-1.2, 1.2)
axins.set_title('Zoomed Region')
axins.grid(True, alpha=0.3)

# 在主图上标记嵌入区域
ax.indicate_inset_zoom(axins, edgecolor='gray')

ax.set_title('Dual Y-Axes with Inset Zoom', fontsize=14)
plt.show()
九、常见问题

1. 图表不显示

  • 确认是否调用了 plt.show()。

  • 在非交互式后端(如 Agg)下必须显式调用 show()。

  • 在 Jupyter Notebook 中,使用 %matplotlib inline 魔法命令确保图表内嵌显示。

2. 刻度太多或顺序错乱

  • 常见原因是将字符串列表当作数据传入(而非数值或日期时间)。

  • Matplotlib 将字符串列表视为分类变量,每个唯一值一个刻度,且按出现顺序排列。

  • 解决方法: 将字符串转换为数值,如 np.asarray(data, dtype='float') 或 np.asarray(data, dtype='datetime64[s]')。

3. 中文显示为方框

  • Matplotlib 默认字体(DejaVu Sans)不含中文字形,需指定支持中文的字体。

  • 设置 plt.rcParams['font.sans-serif'] = ['SimHei', 'Arial Unicode MS', ...] 并确保系统已安装对应字体。

4. 标签重叠或被截断

  • 推荐在创建 Figure 时使用 layout='constrained' 或 layout='compressed' 参数,自动处理标签、标题和图例的重叠问题。

  • 也可使用 fig.tight_layout() 或 fig.subplots_adjust() 手动调整。

5. pcolor 与 pcolormesh 的区别

  • pcolor() 创建 PolyCollection,渲染较慢但更精确。

  • pcolormesh() 创建 QuadMesh,渲染速度更快,是大多数场景的推荐选择。

  • 对于非常大的网格,pcolorfast() 使用 imshow 方式绘制,速度最快但精度最低。

十、小结

本文是 Matplotlib 的参考文档索引,涵盖:

  • 两大接口:Axes 接口(推荐)与 pyplot 接口。

  • 函数索引:按主题归类常用函数入口。

  • pyplot 函数:17 大类,从基本绘图到配置管理。

  • Axes 方法:16 大类,包括绘图、统计、坐标轴控制。

  • Figure 方法:4 大类,管理子图、布局、保存。

  • SubFigure 方法:嵌套子 Figure 的专用方法。

  • 样式配置:内置样式表、rcParams、colormap 速查。

  • 六个示例:从基础折线图到复杂 mosaic 布局。

  • 常见问题:图表不显示、中文方框、标签重叠等。

这份文档适合作为日常开发的参考工具,需要时快速查阅对应功能。

相关资源:

相关推荐
chde2Wang1 小时前
Matplotlib数据可视化学习1
学习·matplotlib
烂蜻蜓3 天前
Matplotlib入门教程(十三):imshow() 详解——灰度图、彩色图、热力图与矩阵可视化
线性代数·矩阵·matplotlib
小小龙学IT3 天前
Python Matplotlib 数据可视化库深度解析
python·信息可视化·matplotlib
烂蜻蜓5 天前
Matplotlib入门教程(十一):饼图详解——pie() 函数与占比可视化
matplotlib
烂蜻蜓5 天前
Matplotlib入门教程(十):柱形图详解——bar() 与 barh() 函数完全指南
matplotlib
ctlover8 天前
Matplotlib
matplotlib
for_ever_love__10 天前
Matplotlib——把训练曲线和分布画出来
matplotlib·数据可视化·大模型开发·训练曲线
茶栀(*´I`*)16 天前
【Python数据可视化】Matplotlib从零到精通:图表核心解剖、多子图布局与三大经典图表实战
python·信息可视化·matplotlib
jzshmyt1 个月前
我用 Python 从零“生成“了一个宇宙,然后让它观察自己(v14)
人工智能·pytorch·python·numpy·matplotlib·空间计算·scipy