正如@hitzg提到的,最常見的方式來完成這樣的事情是使用GridSpec
。 GridSpec
創建一個虛構的網格對象,您可以切片以生成子圖。這是一種簡單的方法來對齊相當複雜的佈局,您想要遵循常規網格。
但是,在這種情況下,如何使用它可能並不明顯。您需要創建一個GridSpec
,numrows * numinsets
行到numcols
列,然後通過間隔numinsets
對其進行切片來創建「主」軸。
在下面的例子(2行,4列,3個插圖),我們就通過gs[:3, 0]
切片得到左上角的「主」軸,gs[3:, 0]
得到左下「主」軸,gs[:3, 1]
得到接下來的上軸等等。對於插圖,每一個都是gs[i, -1]
。
作爲一個完整的例子:
import numpy as np
import matplotlib.pyplot as plt
def build_axes_with_insets(numrows, numcols, numinsets, **kwargs):
"""
Makes a *numrows* x *numcols* grid of subplots with *numinsets* subplots
embedded as "sub-rows" in the last column of each row.
Returns a figure object and a *numrows* x *numcols* object ndarray where
all but the last column consists of axes objects, and the last column is a
*numinsets* length object ndarray of axes objects.
"""
fig = plt.figure(**kwargs)
gs = plt.GridSpec(numrows*numinsets, numcols)
axes = np.empty([numrows, numcols], dtype=object)
for i in range(numrows):
# Add "main" axes...
for j in range(numcols - 1):
axes[i, j] = fig.add_subplot(gs[i*numinsets:(i+1)*numinsets, j])
# Add inset axes...
for k in range(numinsets):
m = k + i * numinsets
axes[i, -1][k] = fig.add_subplot(gs[m, -1])
return fig, axes
def plot(axes):
"""Recursive plotting function just to put something on each axes."""
for ax in axes.flat:
data = np.random.normal(0, 1, 100).cumsum()
try:
ax.plot(data)
ax.set(xticklabels=[], yticklabels=[])
except AttributeError:
plot(ax)
fig, axes = build_axes_with_insets(2, 4, 3, figsize=(12, 6))
plot(axes)
fig.tight_layout()
plt.show()
你真的需要使用'inset_axes'?如何直接將小軸添加到圖中(例如['GridSpec'](http://matplotlib.org/users/gridspec.html))? – hitzg
你說得對。謝謝! –