matplotlib创建多图:比subplots函数更友好的subplot_mosaic函数

新出的fig.subplot_mosaicfig.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可以自定义子图布局,其中

  1. 参数mosaic可以是多行字符串、嵌套列表、ndarray(和嵌套列表差不多,就没有记它,可以在官方文档里自己看)。
  2. 多行字符串中,可以用.表示空白图片,而嵌套列表则可以用参数empty_sentinel自定义表示空白图片的字符串。
  3. 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)

在这里插入图片描述

参考资料:

  1. https://towardsdatascience.com/simplifying-subplots-creation-in-matplotlib-3f6efce356b9 (比较清楚简单)
  2. https://matplotlib.org/stable/gallery/subplots_axes_and_figures/mosaic.html (官方文档,展示了更多复杂组合)
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值