Matplotlib Intermediate Arranging multiple Axes in a Figure

Arranging multiple Axes in a Figure

包含一些最应该使用的工具, 这些工具巩固了 Axes 组织的方式.

Matplotlib 用 Axes 指代包含数据, x,y 轴, 刻度, 标签, 标题等绘图元素的绘图区域. 另一个常用的术语是 subplot, 它指的是与其他 Axes 对象形成网格的 Axes.

Overview

Create grid-shaped combinations of Axes

subplots

subplot_mosaic

SubFigure
子画板
fig.add_subfigure(), subfig.add_subfigure(), fig.subfigures(), subfig,subfigures()等

fig = plt.figure()
sfigs = fig.subfigures(1, 2)
axsL = sfigs[0].subplots(1, 2)
axsR = sfigs[1].subplots(2, 1)
Underlying tools

GridSpec
GridSpec背后的基本思路是”grid”。一个grid(网格)有多个行和列。必须在此之后定义个subplot应该跨越多少网格。

gridspec.GridSpec(
    nrows,
    ncols,
    figure=None,
    left=None,
    bottom=None,
    right=None,
    top=None,
    wspace=None,
    hspace=None,
    width_ratios=None,
    height_ratios=None,
)

SubplotSpec

Adding single Axes at a time

add_axes

subplot or Figure.add_subplot

subplot2grid
一个辅助函数,类似于 pyplot.subplot , 但是使用基于0的索引,并可使子图跨越多个格子。

plt.subplot2grid(shape, loc, rowspan=1, colspan=1, fig=None, **kwargs)
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3)
ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2)
ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
ax4 = plt.subplot2grid((3, 3), (2, 0))
ax5 = plt.subplot2grid((3, 3), (2, 1))

High-level methods for making grids

Basic 2x2 grid

我们用 subplots 生成 2 * 2 子图网格. 它会返回一个 figure 实例和一个 axes 对象数组.

fig, axs = plt.subplots(ncols=2, nrows=2, figsize=(5.5, 3.5),
                        constrained_layout=True)
# add an artist, in this case a nice label in the middle...
# axs
'''
array([[<AxesSubplot:>, <AxesSubplot:>],
       [<AxesSubplot:>, <AxesSubplot:>]], dtype=object)
'''
for row in range(2):
    for col in range(2):
        axs[row, col].annotate(f'axs[{row}, {col}]', 
                               xy = (0.5, 0.5),
                               transform=axs[row, col].transAxes,
                               ha='center', va='center', 
                               fontsize=18,
                               color='darkgrey')
fig.suptitle('plt.subplots()')

默认 xy 坐标是文本左下角的位置, 通过设置 ha = ‘center’, va = ‘center’ 使文本的水平和垂直中心坐标为 xy.

subplot_mosaic 的作用差不多, 不过返回值是一个字典而不是一个数组.

def annotate_axes(ax, text, fontsize=18):
    ax.text(0.5, 0.5, text, transform=ax.transAxes,
            ha="center", va="center", fontsize=fontsize, color="darkgrey")

fig, axd = plt.subplot_mosaic([['upper left', 'upper right'],
                               ['lower left', 'lower right']],
                              figsize=(5.5, 3.5), constrained_layout=True)
                              
# axd
'''
{'upper left': <AxesSubplot:label='upper left'>,
 'upper right': <AxesSubplot:label='upper right'>,
 'lower left': <AxesSubplot:label='lower left'>,
 'lower right': <AxesSubplot:label='lower right'>}
'''
for k in axd:
    annotate_axes(axd[k], f'axd["{k}"]', fontsize=14)
fig.suptitle('plt.subplot_mosaic()')
Axes spanning rows or columns in a grid

subplor_mosaic , GridSpec , subplot2grid 方法都可以做到.

Variable widths or heights in a grid

subplots 和 subplot_mosaic 都允许设置网格的子图有不同的高度宽度, 使用 gridspec_kw 关键字参数.
GridSpec 接收的间距参数可以被传给 subplots 和 subplot_mosaic.

gs_kw = dict(width_ratios=[1.4, 1], height_ratios=[1, 2])
fig, axd = plt.subplot_mosaic([['upper left', 'right'],
                               ['lower left', 'right']],
                              gridspec_kw=gs_kw, figsize=(5.5, 3.5),
                              constrained_layout=True)

和下面的写法类似

g = gridspec.GridSpec(2,2,width_ratios=[1.4, 1], height_ratios=[1, 2])
ax0 = plt.subplot(g[0,0])
ax1 = plt.subplot(g[1,0])
ax2 = plt.subplot(g[:,1])
Nested Axes layouts

嵌套 Axes 布局
有时,拥有两个或多个子图网格会很有帮助 可能不需要彼此相关.请注意,子图布局是独立的,因此每个子图中的轴脊(spines)不是必须对齐的。

Low-level and advanced grid methods

低级和高级网格方法

matplotlib 中实现多个子图的布局,一般需要使用 GridSpecSubplotSpec 两个类。其中,GridSpec 定义了一个网格,可以分割为若干个均匀或不均匀的单元格(cells),GridSpec 的索引返回一个 SubplotSpec , 它是一种网格单元格的子集,可以覆盖一个或多个网格单元格, 可以用于指定一个子图(Axes 对象)的位置。
通过 GridSpecSubplotSpec 类,我们可以实现多种不同的子图排列方式。具体地,对 GridSpec 进行索引,可以获得一个 SubplotSpec 对象,该对象覆盖了一个或多个网格单元格。然后,我们可以使用 SubplotSpec 对象来指定一个 Axes 对象的位置和大小。

Basic 2x2 grid
fig = plt.figure(figsize=(5.5, 3.5), constrained_layout=True)
spec = fig.add_gridspec(ncols=2, nrows=2)
# GridSpec(2, 2) <Figure size 550x350 with 0 Axes>
type(spec[0,0]), type(spec)
# (matplotlib.gridspec.SubplotSpec, matplotlib.gridspec.GridSpec)
ax0 = fig.add_subplot(spec[0, 0])
annotate_axes(ax0, 'ax0')

ax1 = fig.add_subplot(spec[0, 1])
annotate_axes(ax1, 'ax1')

ax2 = fig.add_subplot(spec[1, 0])
annotate_axes(ax2, 'ax2')

ax3 = fig.add_subplot(spec[1, 1])
annotate_axes(ax3, 'ax3')

fig.suptitle('Manually added subplots using add_gridspec')
Axes spanning rows or grids in a grid

可以用 numpy 切片语法 来索引 spec 数组.

```python
import matplotlib.gridspec as gridspec
gs = gridspec.GridSpec(3,3)
ax1 = plt.subplot(gs[0,:])
ax2 = plt.subplot(gs[1,:-1])
ax3 = plt.subplot(gs[1:,-1])
ax4 = plt.subplot(gs[2,0])
ax5 = plt.subplot(gs[-1,1])
plt.tight_layout()
Manual adjustments to a GridSpec layout

如果你明确使用了 GridSpec, 你可以调整由其创建的子图的参数的布局
注意, 这种选择与 contrained_layout 和 tight_layout 不兼容, 因为这俩都会忽略 left 和 right 并且会调整子图的大小以填充 figure.通常这样的手动放置需要迭代以使刻度标签不与 Axes 重叠.

fig = plt.figure(constrained_layout=False, facecolor='0.9')
gs = fig.add_gridspec(nrows=3, ncols=3, left=0.05, right=0.75,
                      hspace=0.1, wspace=0.05)
ax0 = fig.add_subplot(gs[:-1, :])
annotate_axes(ax0, 'ax0')
ax1 = fig.add_subplot(gs[-1, :-1])
annotate_axes(ax1, 'ax1')
ax2 = fig.add_subplot(gs[-1, -1])
annotate_axes(ax2, 'ax2')
fig.suptitle('Manual gridspec with right=0.75')
Nested layouts with SubplotSpec

嵌套布局 subgridspec

fig = plt.figure(constrained_layout=True)
gs0 = fig.add_gridspec(1, 2)

gs00 = gs0[0].subgridspec(2, 2)
gs01 = gs0[1].subgridspec(3, 1)

for a in range(2):
    for b in range(2):
        ax = fig.add_subplot(gs00[a, b])
        annotate_axes(ax, f'axLeft[{a}, {b}]', fontsize=10)
        if a == 1 and b == 1:
            ax.set_xlabel('xlabel')
for a in range(3):
    ax = fig.add_subplot(gs01[a])
    annotate_axes(ax, f'axRight[{a}, {b}]')
    if a == 2:
        ax.set_ylabel('ylabel')

fig.suptitle('nested gridspecs')

涉及利用 gridspec 的 subplots 方法创建(rows, cols)个子图对象

fig = plt.figure()
g = gridspec.GridSpec(2,2)
ax = g.subplots()
# GridSpec.subplots() only works for GridSpecs created with a parent figure

GridSpec.subplots() 方法只适用于已经被分配给一个父级 figure 的 GridSpec 对象。
解决方法: 分配一个父级 figure.

fig = plt.figure()
g = gridspec.GridSpec(2,2,figure = fig)
# 或
# g = fig.add_gridspec(2,2)
ax = g.subplots()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值