在matplotlib子图

时间:2018-02-02 14:24:06

标签: python matplotlib subplot

我经常使用matplotlibs子图,我会这样:

import mumpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots(3, 2, figsize=(8, 10), sharey='row',
                       gridspec_kw={'height_ratios': [1, 2, 2]})
ax[0, :].plot(np.random.randn(128))

ax[1, 0].plot(np.arange(128))
ax[1, 1].plot(1 / (np.arange(128) + 1))

ax[2, 0].plot(np.arange(128) ** (2))
ax[2, 1].plot(np.abs(np.arange(-64, 64)))

我想在这个(修改过的)gridspec示例中为2个位置创建一个像ax1所做的单个绘图的图:

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

fig = plt.figure()

gs = GridSpec(3, 3)
ax1 = plt.subplot(gs[0, :])
# identical to ax1 = plt.subplot(gs.new_subplotspec((0, 0), colspan=3))
ax2 = plt.subplot(gs[1, :-1])
ax3 = plt.subplot(gs[1:, -1])
ax4 = plt.subplot(gs[-1, 0])
ax5 = plt.subplot(gs[-1, -2])

fig.suptitle("GridSpec")

plt.show()

请参阅完整示例:https://matplotlib.org/gallery/userdemo/demo_gridspec02.html#sphx-glr-gallery-userdemo-demo-gridspec02-py

由于我正在使用子图环境,我会知道这是否可行。另外因为子图可以处理GridSpec参数。可惜的是,并没有真正解释例​​外是什么。

1 个答案:

答案 0 :(得分:1)

plt.subplots提供了一种创建完全填充的gridspec的便捷方法。 例如,而不是

fig = plt.figure()
n = 3; m=3
gs = GridSpec(n, m)
axes = []
for i in range(n):
    row = []
    for j in range(m):
        ax = fig.add_subplot(gs[i,j])
        row.append(ax)
    axes.append(row)
axes = np.array(axes)

你可以写一行

n = 3; m=3
fig, axes = plt.subplots(ncols=m, nrows=n)

但是,如果您希望自由选择要填充网格上的哪些位置,或者甚至要包含跨越多个行或列的子图,plt.subplots将无济于事,因为它没有任何选项来指定gridspec占据的位置。 从这个意义上讲,文档很清楚:由于它没有记录任何可用于实现非直线网格的参数,因此只需 就没有这样的选项。

是否选择使用plt.subplotsgridspec则是所需情节的问题。可能存在两者的组合仍然有用的情况,例如

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

n=3;m=3
gridspec_kw = dict(height_ratios=[3,2,1])
fig, axes  = plt.subplots(ncols=m, nrows=n, gridspec_kw=gridspec_kw)

for ax in axes[1:,2]:
    ax.remove()

gs = GridSpec(3, 3, **gridspec_kw)
fig.add_subplot(gs[1:,2])

plt.show()

首先定义通常的网格,并且仅在我们需要行跨越图的位置,我们移除轴并使用gridspec创建一个新的。

enter image description here