看着matplotlib
文档,这似乎是添加 AxesSubplot
的标准方法到 Figure
是使用 Figure.add_subplot
:
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
中是否可行?如果是这样,我该怎么做?更新:我还没有设法将轴和图形的创建解耦,但是按照下面答案中的示例,可以轻松地在新的或 olf 图形实例中重新使用以前创建的轴。这可以用一个简单的函数来说明:
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)
此外,您可以简单地将轴实例添加到另一个图形:
import matplotlib.pyplot as plt
fig1, ax = plt.subplots()
ax.plot(range(10))
fig2 = plt.figure()
fig2.axes.append(ax)
plt.show()
调整它的大小以匹配其他子情节“形状”也是可能的,但它会很快变得比它值得的麻烦。根据我的经验,对于复杂情况,仅传递图形或轴实例(或实例列表)的方法要简单得多......
关于python - matplotlib:我可以创建 AxesSubplot 对象,然后将它们添加到 Figure 实例吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49069712/