matplotlib 操作子图(subplot,axes)

Matplotlib 中文用户指南 3.3 使用 GridSpec 自定义子图位置

  • ax:matplotlib.axes._subplots.AxesSubplot,的基本操作
    • ax.set_xticks([]), ax_set_yticks([]):关闭坐标刻度
    • ax.axis('off'):关闭坐标轴
    • ax.set_title():设置标题

1. subplots

fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(8, 4))
ax[0].plot(...)
ax[0].set_xlabel(...)
ax[0].set_title(...)

ax[1].plot(...)
ax[1].set_xlabel(...)
...
fig, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex=True)

更一般的做法(也是matlab的风格)是这样的:

fig = plt.figure()          # 创建一个figure对象,底下的一切显示均在此figure上完成

plt.subplot(121)
plt.imshow(img1)
plt.subplot(122)
plt.imshow(img2)

plt.show()

# 当然放在一个range里边
for i in range(ndim):
    plt.subplot(ndim//5, 5, i+1)
    plt.hist()

2. subplot2grid

  • subplot2grid

    
    # 以下两条语句等价
    
    ax = plt.subplot2grid((2,2),(0, 0))
    ax = plt.subplot(221)       # 下标从 0 开始
    • colspan、rowspan 与 索引的对应关系
    import matplotlib.pyplot as plt
    
    def disable_axis(ax):
        ax.set_xticks([])
        ax.set_yticks([])
        # ax.axis('off')
    
    def set_title(ax, title):
        ax.set_title(title)
    
    def subplot2grid_demo():
        ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=2)
        disable_axis(ax1)
        set_title(ax1, 'ax1')
        ax2 = plt.subplot2grid((3, 3), (1, 0))
        disable_axis(ax2)
        set_title(ax2, 'ax2')
        ax3 = plt.subplot2grid((3, 3), (1, 1))
        disable_axis(ax3)
        set_title(ax3, 'ax3')
        ax4 = plt.subplot2grid((3, 3), (0, 2), rowspan=2)
        disable_axis(ax4)
        set_title(ax4, 'ax4')
        ax5 = plt.subplot2grid((3, 3), (2, 0), colspan=3)
        disable_axis(ax5)
        set_title(ax5, 'ax5')
        # plt.xticks([])
        # plt.yticks([])
        # plt.axis('off')
        plt.show()
    
    if __name__ == '__main__':
        subplot2grid_demo()



3. GridSpec:方便的切片操作

GridSpec 提供了十分方便的切片操作,实现上述功能,则只需如下代码:

def gridspec_demo():
    gs = gridspec.GridSpec(3, 3)
    ax1 = plt.subplot(gs[0, :2])
    ax2 = plt.subplot(gs[1, 0])
    ax3 = plt.subplot(gs[1, 1])
    ax4 = plt.subplot(gs[0:2, 2])
    ax5 = plt.subplot(gs[2:, :])
    plt.show()
  • 3
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

五道口纳什

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值