本篇博客详细介绍了如何使用Matplotlib v3.4及以上版本绘制包含多个子图区域的图文件,此处的子图与子绘图区域(axes)有所区别。本篇博客内容参考了官方文档Figure subfigures,并在此基础上进一步取舍和补充,仅供学习和参考。🚀🚀🚀
简介
在使用Python的绘图库Matplotlib进行科研等绘图时,有时我们希望一个Figure中能有多个子图(subfigure),而不仅仅是多个Axes绘图区域。这个可以通过嵌套使用Matplotlib自带的布局管理工具gridspec实现。但是,有的时候一个拥有自己绘图元素的专业子图API更是人们希望的。庆幸的是,在Matplotlib的v3.4版本之后自带了两个创建子图的API:
matplotlib.figure.Figure.add_subfigure:为某个figure添加一个子图。- 参数:
- subplotspec: gridspec.SubplotSpec类型. 定义父图网格中子图放置区域的位置.
- **kwargs: 其它关键字参数. 参考Subfigure
- 参数:
matplotlib.figure.Figure.subfigures:为某个figure创建多个子图。- 参数:
- nrows, ncols: int类型, 默认为1. 子图的行数和列数.
- squeeze:bool类型, 默认为Ture. 是否从返回的子图数组中挤出额外的维度.
- wspace, hspace: float类型, 默认为None. 子图之间间隔的宽度/高度.
- width_ratios: array-like类型, 定义子图列的相对宽度. 可选项.
- height_ratio: array-like类型, 定义子图行的相对高度. 可选项.
- 返回值: 返回多个子图的集合.
- 参数:
检查自己的Matplotlib版本和支持的字体
# 查看Matplotlib版本
import matplotlib
print(f"The Matplotlib version is: {matplotlib.__version__}")
# 查看Matplotlib的字体参数
font_list = sorted([f.name for f in matplotlib.font_manager.fontManager.ttflist])
for ft in font_list:
print(ft)
The Matplotlib version is: 3.7.0
Agency FB
Agency FB
Algerian
Arial
...
子图绘图示例
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.family'] = 'SimHei' # 设置Matplotlib的字体为黑体, 进而正常显示中文
plt.rcParams['axes.unicode_minus'] = False # 用于在中文字体环境下正常显示负号
def example_plot(ax, fontsize=12, hide_labels=False):
"""示例绘图函数"""
pc = ax.pcolormesh(np.random.randn(30, 30), vmin=-2.5, vmax=2.5)
if not hide_labels:
ax.set_xlabel('x-label', fontsize=fontsize)
ax.set_ylabel('y-label', fontsize=fontsize)
ax.set_title('Title', fontsize=fontsize)
return pc
np.random.seed(19680808)
# 子图嵌套,基于gridspec实现
fig = plt.figure(layout='constrained', figsize=(10, 4))
subfigs = fig.subfigures(1, 2, wspace=0.07) # 创建一行两列两个子图
# 左侧子图绘制
axsLeft = subfigs[0].subplots(1, 2, sharey=True) # 左边子图的两个Axes
subfigs[0].set_facecolor('0.75')
for ax in axsLeft:
pc = example_plot(ax)
subfigs[0].suptitle('左侧子图', fontsize='x-large')
subfigs[0].colorbar(pc, shrink=0.6, ax=axsLeft, location='bottom')
# 右侧子图绘制
axsRight = subfigs[1].subplots(3, 1, sharex=True)
for nn, ax in enumerate(axsRight):
pc = example_plot(ax, hide_labels=True)
if nn == 2:
ax.set_xlabel('横坐标')
if nn == 1:
ax.set_ylabel('纵坐标')
subfigs[1].set_facecolor('0.85')
subfigs[1].colorbar(pc, shrink=0.6, ax=axsRight)
subfigs[1].suptitle('右侧子图', fontsize='x-large')
fig.suptitle('主绘图', fontsize='x-large') # 主绘图大标题
plt.show()
绘制结果如下图所示。

参考文献
- The matplotlib development team. Figure subfigures[EB/OL]. [2024-09-11]. https://matplotlib.org/stable/gallery/subplots_axes_and_figures/subfigures.html#sphx-glr-gallery-subplots-axes-and-figures-subfigures-py
- The matplotlib development team. Nested Gridspecs[EB/OL]. [2024-09-11]. https://matplotlib.org/stable/gallery/subplots_axes_and_figures/gridspec_nested.html
- The matplotlib development team. matplotlib.figure.Figure.subfigures[EB/OL]. [2024-09-11]. https://matplotlib.org/stable/api/_as_gen/matplotlib.figure.Figure.subfigures.html#matplotlib.figure.Figure.subfigures
- The matplotlib development team. matplotlib.figure.Figure.add_subfigure[EB/OL]. [2024-09-11]. https://matplotlib.org/stable/api/_as_gen/matplotlib.figure.Figure.add_subfigure.html#matplotlib.figure.Figure.add_subfigure
收集整理和创作不易, 若有帮助🉑, 请帮忙点赞👍➕收藏❤️, 谢谢!✨✨🚀🚀
1953

被折叠的 条评论
为什么被折叠?



