Python 从matplotlib子批次中的多列生成单打印

Python 从matplotlib子批次中的多列生成单打印,python,matplotlib,subplot,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].p

我经常使用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示例中,该图形在两个位置有一个单独的绘图,如为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()
有关完整示例,请参见:


因为我经常使用子地块环境,所以我知道这是否也是可能的。还因为子地块可以处理GridSpec参数。遗憾的是,它没有真正解释什么是异常。

plt.子包提供了一种创建完全填充的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.subplot
不会有多大帮助,因为它没有任何选项来指定要占用的gridspec位置。 从这个意义上讲,文档非常清楚:因为它没有记录任何可以用来实现非直线网格的参数,所以根本没有这样的选项

选择使用
plt.subplot
还是
gridspec
则是所需绘图的问题。在某些情况下,这两种方法的结合在某种程度上仍然有用,例如:

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创建一个新的轴


你到底想做什么?在不使用GridSpec的情况下,让顶部子地块跨越2列,但保持其余部分不变?