是否可以在 matplotlib 轴中嵌入数量不断变化的绘图?例如,inset_axes
方法用于将插入轴放置在父轴内:
但是,我有几行图,我想在每行的最后一个轴对象中包含一些插入轴。
fig, ax = plt.subplots(2,4, figsize=(15,15))
for i in range(2):
ax[i][0].plot(np.random.random(40))
ax[i][2].plot(np.random.random(40))
ax[i][3].plot(np.random.random(40))
# number of inset axes
number_inset = 5
for j in range(number_inset):
ax[i][4].plot(np.random.random(40))
这里不是最后一列中绘制的 5 个图,我想要几个包含图的插入轴。像这样:
这样做的原因是每一行都指向要绘制的不同项目,最后一列应该包含此类项目的组件。有没有一种方法可以在 matplotlib 中执行此操作,或者是否有其他方法可以将其可视化?
谢谢
最佳答案
正如@hitzg 所提到的,完成此类任务的最常见方法是使用GridSpec
。 GridSpec
创建一个虚构的网格对象,您可以对其进行切片以生成子图。这是一种将您想要遵循规则网格的相当复杂的布局对齐的简单方法。
但是,在这种情况下如何使用它可能不是很明显。您需要通过 numcols
列创建一个包含 numrows * numinsets
行的 GridSpec
,然后通过按间隔对其进行切片来创建“主”轴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()
关于python - 使用 matplotlib 在另一个轴中嵌入多个插入轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27700625/