查看matplotlib文档,向Figure添加AxesSubplot的标准方法似乎是使用Figure.add_subplot
from matplotlib import pyplot
fig = pyplot.figure()
ax = fig.add_subplot(1,1,1)
ax.hist( some params .... )我希望能够独立于图形创建AxesSubPlot-like对象,这样我就可以在不同的图形中使用它们。有点像
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中是可能的吗?如果是的话,我如何做到这一点?
更新:I还没有成功地将轴和图形的创建解耦,但是下面的答案中的例子可以很容易地重用以前创建的轴在新的或O尔夫图形实例中。这可以用一个简单的函数来说明:
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发布于 2011-06-10 16:54:31
通常,只需将axes实例传递给函数即可。
例如:
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)此外,您也可以简单地向另一个图形添加一个axes实例:
import matplotlib.pyplot as plt
fig1, ax = plt.subplots()
ax.plot(range(10))
fig2 = plt.figure()
fig2.axes.append(ax)
plt.show()调整大小以匹配其他子图“形状”也是可能的,但它很快就会变得比它的价值更麻烦。在我的经验中,简单地传递图形或轴实例(或实例列表)的方法对于复杂情况来说要简单得多.
发布于 2017-10-24 09:15:49
下面显示了如何将轴从一个图形“移动”到另一个图形。这是@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()发布于 2011-06-10 17:58:23
对于行图,您可以处理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])https://stackoverflow.com/questions/6309472
复制相似问题