新出的fig.subplot_mosaic
比fig.subplots()
直观很多,小白如我也轻松搞懂。学到的时候泪流满面,为啥没早发现它TvT。
基础导入
import matplotlib.pyplot as plt
%matplotlib inline
魔术命令,作用是在Notebook内显示图像,而不需要显式地调用plt.show()。
%matplotlib notebook
同上,但允许交互式操作(例如缩放、平移、下载图片)
(试用下来感觉比plotly的功能简陋很多,但是操作毕竟更简便。只能说适合自己随便用用。)
创建子图
# 官方给出的一个帮助理解子图排布关系的函数,它并非是必要的
def identify_axes(ax_dict, fontsize=48):
"""
Helper to identify the Axes in the examples below.
Draws the label in a large font in the center of the Axes.
Parameters
----------
ax_dict : dict[str, Axes]
Mapping between the title / label and the Axes.
fontsize : int, optional
How big the label should be.
"""
kw = dict(ha="center", va="center", fontsize=fontsize, color="darkgrey")
for k, ax in ax_dict.items():
ax.text(0.5, 0.5, k, transform=ax.transAxes, **kw)
经典四格布局
fig=plt.figure(layout='constrained')
mosaic = [['a','b'],['c','d']] # 创造四格布局
# mosaic = "AB;CD" # 等价上一句
ax_dict=fig.subplot_mosaic(mosaic)
# 每个子表各自绑定要画的图
ax_dict['a'].plot([1,2,3])
ax_dict['b'].scatter([1,2,3],[4,5,6])
ax_dict['c'].hist([1,2,3,4,5])
ax_dict['d'].bar([1,2,3],[2,4,6])
identify_axes(ax_dict)
自定义跨轴布局
使用多行字符串
# 自定义更复杂的布局
fig = plt.figure(layout='constrained')
mosaic ='''
abd
ccd
'''
ax_dict = fig.subplot_mosaic(mosaic) # 把列表换成多行字符串
identify_axes(ax_dict)
使用嵌套列表
列表可以无限嵌套,达到和字符串排布一样的效果。
inner = [
["inner A"],
["inner B"],
]
outer_nested_mosaic = [
["main", inner],
["bottom", "bottom"],
]
axd = plt.figure(layout="constrained").subplot_mosaic(
outer_nested_mosaic, empty_sentinel=None
)
identify_axes(axd, fontsize=36)
空白的表达方式
# 还可以插入空白图片
fig = plt.figure(layout='constrained')
mosaic ='''
a.c
bbb
.d.
'''
ax_dict = fig.subplot_mosaic(mosaic)
identify_axes(ax_dict)
# 可以自定义代表空白图片的字符,不一定是“.”
axd = plt.figure(layout="constrained").subplot_mosaic(
[
["main", "zoom"],
["main", "BLANK"],
],
empty_sentinel="BLANK", # 自定义代表空白图片的字符
width_ratios=[2, 1],
)
identify_axes(axd)
自定义相对宽度高度比
mosaic = """
.a.
bAc
.d.
"""
axd = plt.figure(layout="constrained").subplot_mosaic(
mosaic,
height_ratios=[1, 3.5, 1], # 高度比(从上到下)
# set the width ratios between the columns
width_ratios=[1, 3.5, 1], # 宽度比(从左到右)
)
identify_axes(axd)
小结
函数subplot_mosaic
可以自定义子图布局,其中
- 参数mosaic可以是多行字符串、嵌套列表、ndarray(和嵌套列表差不多,就没有记它,可以在官方文档里自己看)。
- 多行字符串中,可以用.表示空白图片,而嵌套列表则可以用参数empty_sentinel自定义表示空白图片的字符串。
- height_ratios、width_ratios可以改变高度、宽度比例,传入内容是列表。
一个同时涵盖以上所有参数的subplot_mosaic应用例:
mosaic = """
.a.
bAc
.d.
"""
axd = plt.figure(layout="constrained").subplot_mosaic(
mosaic,
height_ratios=[1, 3.5, 1], # 高度比(从上到下)
width_ratios=[1, 3.5, 1], # 宽度比(从左到右)
)
identify_axes(axd)
# 等价于:
mosaic = [['blank', 'a', 'blank'], ['b', 'A', 'c'], ['blank', 'd', 'blank']]
axd = plt.figure(layout="constrained").subplot_mosaic(
mosaic,
empty_sentinel = 'blank',
height_ratios=[1, 3.5, 1], # 高度比(从上到下)
width_ratios=[1, 3.5, 1], # 宽度比(从左到右)
)
identify_axes(axd)
参考资料: