我真的不明白在pyplot中使用了一些数字对象。
假设我用plt.figure()制作了两个带有两个数字(1,2)的图。
plt.figure(1, figsize=(10,4))
plt.subplot(1, 3, 1)
plt.bar(category, values)
plt.subplot(1, 3, 2)
plt.scatter(category, values)
plt.subplot(1, 3, 3)
plt.plot(category, values)
plt.suptitle('multiple plotting')
plt.show()
plt.figure(2, figsize=(10,5))
plt.subplot(3, 1, 1)
plt.bar(category, values)
plt.subplot(3, 1, 2)
plt.scatter(category, values)
plt.subplot(3, 1, 3)
plt.plot(category, values)
plt.suptitle('multiple plotting')
plt.show()
然后......当我想再次绘制图1时,我该怎么办?
我想我可以理解如何设置一个数字,但是当我使用它以及如何使用它时真的不明白。
感谢您提前解释!
在您的情况下,我会将句柄存储到子图中(参见下面的示例)。通过这种方式,您可以稍后再次通过以下方式处理任何子图:handle.plot(...)
import numpy as np
import matplotlib.pyplot as plt
plt.figure(1, figsize=(10,4))
ax1 = plt.subplot(1, 3, 1)
ax1.plot(np.random.rand(3,2))
ax2 = plt.subplot(1, 3, 2)
ax2.plot(np.random.rand(3,2))
ax3 = plt.subplot(1, 3, 3)
ax3.plot(np.random.rand(3,2))
plt.suptitle('multiple plotting')
ax1.plot(np.random.rand(3,2)) # Plot in first subplot again
ax2.plot(np.random.rand(3,2)) # Plot in second subplot again
plt.show()
如果要使用数字来处理子图,可以执行以下操作:
fig,ax = plt.subplots(nrows=1,ncols=3,figsize=(10,4))
ax[0].plot(np.random.rand(3,2))
ax[1].plot(np.random.rand(3,2))
ax[2].plot(np.random.rand(3,2))
plt.suptitle('multiple plotting')
ax[0].plot(np.random.rand(3,2))
ax[1].plot(np.random.rand(3,2))
plt.show()
希望这有帮助!
在调用plt.show()
之后,你无法再次绘制这些数字(除非你在一些互动环节(?))。所以我们假设你没有打电话给plt.show()
。在这种情况下,您可以通过figure(1)
重新激活第一个数字。
plt.figure(1, figsize=(10,4))
plt.plot(...)
plt.figure(2, figsize=(10,5))
plt.plot(...)
plt.figure(1)
plt.plot(...) # <--- This plots to figure 1 again.
plt.show()
只需查看pyplot.figure
的官方文档,您就可以实例化Figure
,它是:
所有情节元素的顶级容器。
因此,重用一个图形实例的简单方法是:
import numpy as np
import matplotlib.pyplot as plt
def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
def g(t):
return np.sin(t) * np.cos(1/(t+0.1))
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
fig = plt.figure(1, figsize=(10,4))
fig.suptitle('First figure instance')
plt.figure(2, figsize=(10,5))
plt.subplot(1, 2, 1)
plt.bar(t1, f(t1))
plt.subplot(1, 2, 2)
plt.scatter(t2, g(t2))
plt.suptitle('second plot')
plt.show()
sub1 = fig.add_subplot(221)
sub1.plot(t1, g(t1))
sub2 = fig.add_subplot(224)
sub2.plot(t2, f(t2))
fig.savefig("first_figure.png", dpi=200)