如何在for循环中使用matplotlib处理多个数字

时间:2018-06-13 09:50:58

标签: python-3.x matplotlib

我想在两个不同的数字中只用一个循环绘制不同的东西(我有一个巨大的矩阵,我不想把2个循环),如下所示:

plt.figure(0)
plt.figure(1)
for i in range(10):
   #plot it only on the figure(0)
   plt.plot(np.arange(10), np.power(np.arange(10), i), label = 'square') 
   #plot it only on the figure(1)
   plt.plot(np.arange(10), np.power(np.arange(10), 1/i), label = '1/square') 
   plt.legend() #if it does for both figures seperately
plt.show()

我怎样才能做到这一点?非常感谢。

1 个答案:

答案 0 :(得分:2)

使用pyplot状态接口

你需要激活"在绘制它之前的相应数字。

plt.figure(0)
plt.figure(1)

for i in range(10):
   #plot it only on the figure(0)
   plt.figure(0)
   plt.plot(np.arange(10), np.power(np.arange(10), i), label = 'square') 
   #plot it only on the figure(1)
   plt.figure(1)
   plt.plot(np.arange(10), np.power(np.arange(10), 1/i), label = '1/square')

#legend for figure(0)
plt.figure(0)
plt.legend()
#legend for figure(1)
plt.figure(1)
plt.legend()
plt.show()

使用面向对象的样式

直接使用对象及其方法。

fig0, ax0 = plt.subplots()
fig1, ax1 = plt.subplots()
for i in range(10):
   #plot it only on the fig0
   ax0.plot(np.arange(10), np.power(np.arange(10), i), label = 'square') 
   #plot it only on the fig1
   ax1.plot(np.arange(10), np.power(np.arange(10), 1/i), label = '1/square') 

ax0.legend()
ax1.legend()
plt.show()