问题描述
查看 matplotlib
文档,将 AxesSubplot
添加到 Figure
的标准方法似乎是使用 Figure.add_subplot
:
Looking at the matplotlib
documentation, it seems the standard way to add an AxesSubplot
to a Figure
is to use Figure.add_subplot
:
from matplotlib import pyplot
fig = pyplot.figure()
ax = fig.add_subplot(1,1,1)
ax.hist( some params .... )
我希望能够独立于图形创建类似 AxesSubPlot
的对象,以便我可以在不同的图形中使用它们.类似的东西
I would like to be able to create AxesSubPlot
-like objects independently of the figure, so I can use them in different figures. Something 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
中是否可行,如果可以,我该怎么做?
Is this possible in matplotlib
and if so, how can I do this?
更新:我还没有设法将轴和图形的创建解耦,但是按照下面答案中的示例,可以轻松地在新的或 olf 图形实例中重新使用以前创建的轴.这可以用一个简单的函数来说明:
Update: I have not managed to decouple creation of Axes and Figures, but following examples in the answers below, can easily re-use previously created axes in new or olf Figure instances. This can be illustrated with a simple function:
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
推荐答案
通常,您只需将坐标区实例传递给函数.
Typically, you just pass the axes instance to a function.
例如:
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()
要回答您的问题,您可以随时执行以下操作:
To respond to your question, you could always do something like this:
def subplot(data, fig=None, index=111):
if fig is None:
fig = plt.figure()
ax = fig.add_subplot(index)
ax.plot(data)
此外,您可以简单地将轴实例添加到另一个图形中:
Also, you can simply add an axes instance to another figure:
import matplotlib.pyplot as plt
fig1, ax = plt.subplots()
ax.plot(range(10))
fig2 = plt.figure()
fig2.axes.append(ax)
plt.show()
调整它的大小以匹配其他子情节形状"也是可能的,但它会很快变得比它值得的麻烦.根据我的经验,对于复杂情况,仅传递图形或轴实例(或实例列表)的方法要简单得多...
Resizing it to match other subplot "shapes" is also possible, but it's going to quickly become more trouble than it's worth. The approach of just passing around a figure or axes instance (or list of instances) is much simpler for complex cases, in my experience...
这篇关于matplotlib:我可以创建 AxesSubplot 对象,然后将它们添加到 Figure 实例吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!