首页 > 解决方案 > 在子图中使用现有图

问题描述

我原则上知道如何用子图做数字。我想做的是创建一些只包含一把斧头的人物。随后,我想在同一个子图中进一步使用它们,而无需再次创建它们。下面是我所拥有的。

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0, 2*np.pi, 0.01)
y1 = np.sin(x)
y2 = np.sin(2*x)

plt.clf()
fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
ax1.plot(x,y1)

fig2 = plt.figure()
ax2 = fig2.add_subplot(111)
ax2.plot(x,y2)

现在我想在一个新的数字内使用ax1和。ax2如果不再次指定地块,我怎么能做到这一点?在我的实际代码中,有很多选项需要设置,我想避免这种情况。就像是

fig3 = plt.figure()
ax1 = fig3.add_subplot(121)
ax2 = fig3.add_subplot(122)

这样上面定义的轴就可以在一个新的图形中并排重复使用。

编辑:我找到了解决方案。事实证明,实际上不可能使用已定义的轴,因为轴的定义包括它是否是子图。相反,我沿着这些思路做了一些事情:

fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.plot(data)
ax2.plot(data)
fig.show()

这样,轴的规格在很大程度上独立于定义整体图。

标签: pythonmatplotlibsubplot

解决方案


推荐阅读