matplotlib:我可以创buildAxesSubplot对象,然后将它们添加到graphics实例?

查看matplotlib文档,似乎将AxesSubplot添加到Figure的标准方法是使用Figure.add_subplot

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

我希望能够独立于graphics创buildAxesSubPlot类对象,所以我可以在不同的graphics中使用它们。 就像是

 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 ,如果是这样,我该怎么做?

更新:我还没有设法分离轴和graphics的创build,但下面的答案中的例子,可以很容易地重新使用以前创build的新的或新的graphics实例轴。 这可以用一个简单的函数来说明:

 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 

通常情况下,您只需将轴实例传递给函数。

例如:

 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) 

另外,您可以简单地将轴实例添加到另一个graphics中:

 import matplotlib.pyplot as plt fig1, ax = plt.subplots() ax.plot(range(10)) fig2 = plt.figure() fig2.axes.append(ax) plt.show() 

调整其大小以匹配其他子图“形状”也是可能的,但它将很快变得比它的价值更麻烦。 根据我的经验,仅仅传递graphics或坐标轴实例(或实例列表)的方法对于复杂的情况要简单得多…

对于线图,您可以自行处理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]) 

下面显示了如何将一个坐标轴从一个graphics移动到另一个坐标系。 这是@ JoeKington最后一个例子的预期function,在更新的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()