我可以创建AxesSubplot对象,然后将它们添加到Figure实例中吗?

113 投票
5 回答
111938 浏览
提问于 2025-04-16 19:20

在查看 matplotlib 的文档时,发现标准的方法是通过 Figure.add_subplot 来给 Figure 添加一个 AxesSubplot

from matplotlib import pyplot

fig = pyplot.figure()
ax = fig.add_subplot(1,1,1)
ax.hist( some params .... )

我希望能够独立于图形创建 AxesSubPlot 类似的对象,这样我就可以在不同的图形中使用它们。就像这样:

fig = pyplot.figure()
histoA = some_axes_subplot_maker.hist( some params ..... )
histoA = some_axes_subplot_maker.hist( some other params ..... )
# make one figure with both plots
fig.add_subaxes(histo1, 211)
fig.add_subaxes(histo1, 212)
fig2 = pyplot.figure()
# make a figure with the first plot only
fig2.add_subaxes(histo1, 111)

matplotlib 中,这可能吗?如果可以的话,我该怎么做呢?

更新:我还没有成功将坐标轴和图形的创建分开,但根据下面回答中的例子,我可以很容易地在新的或旧的图形实例中重用之前创建的坐标轴。这可以通过一个简单的函数来说明:

def plot_axes(ax, fig=None, geometry=(1,1,1)):
    if fig is None:
        fig = plt.figure()
    if ax.get_geometry() != geometry :
        ax.change_geometry(*geometry)
    ax = fig.axes.append(ax)
    return fig

5 个回答

4

对于线形图,你可以直接使用 Line2D 这个对象来处理。

fig1 = pylab.figure()
ax1 = fig1.add_subplot(111)
lines = ax1.plot(scipy.randn(10))

fig2 = pylab.figure()
ax2 = fig2.add_subplot(111)
ax2.add_line(lines[0])
39

下面的内容展示了如何将一个坐标轴“移动”到另一个图形中。这是@JoeKington最后一个例子的预期功能,但在较新的matplotlib版本中,这个方法不再有效,因为一个坐标轴不能同时存在于多个图形中。

你首先需要把坐标轴从第一个图形中移除,然后把它添加到下一个图形中,并为它指定一个位置。

import matplotlib.pyplot as plt

fig1, ax = plt.subplots()
ax.plot(range(10))
ax.remove()

fig2 = plt.figure()
ax.figure=fig2
fig2.axes.append(ax)
fig2.add_axes(ax)

dummy = fig2.add_subplot(111)
ax.set_position(dummy.get_position())
dummy.remove()
plt.close(fig1)

plt.show()
57

通常情况下,你只需要把坐标轴的实例传给一个函数就可以了。

比如说:

import matplotlib.pyplot as plt
import numpy as np

def main():
    x = np.linspace(0, 6 * np.pi, 100)

    fig1, (ax1, ax2) = plt.subplots(nrows=2)
    plot(x, np.sin(x), ax1)
    plot(x, np.random.random(100), ax2)

    fig2 = plt.figure()
    plot(x, np.cos(x))

    plt.show()

def plot(x, y, ax=None):
    if ax is None:
        ax = plt.gca()
    line, = ax.plot(x, y, 'go')
    ax.set_ylabel('Yabba dabba do!')
    return line

if __name__ == '__main__':
    main()

针对你的问题,你可以这样做:

def subplot(data, fig=None, index=111):
    if fig is None:
        fig = plt.figure()
    ax = fig.add_subplot(index)
    ax.plot(data)

另外,你也可以把一个坐标轴的实例添加到另一个图形里:

import matplotlib.pyplot as plt

fig1, ax = plt.subplots()
ax.plot(range(10))

fig2 = plt.figure()
fig2.axes.append(ax)

plt.show()

调整大小以匹配其他子图的“形状”也是可以的,但这样做很快就会变得麻烦,得不偿失。根据我的经验,简单地传递一个图形或坐标轴的实例(或者实例的列表)在处理复杂情况时要简单得多……

撰写回答