如何在for循环中使用Matplotlib处理多个图形 [英] How to handle multi figures with matplotlib in a for loop

查看:78
本文介绍了如何在for循环中使用Matplotlib处理多个图形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想在1个循环中将不同的事物绘制在两个不同的图形中(我有一个巨大的矩阵,我不想在循环中放置2个),如下所示:

I want to plot different things in two different figures in only 1 loop (I have a huge matrice that I don't want to put 2 for loops) like the following:

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()

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

How can I achieve this? Thanks a lot.

推荐答案

使用 pyplot state-like interface

您需要激活"绘制之前的各个图.

Using the pyplot state-like interface

You would need to "activate" the respective figure before plotting to it.

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()

使用面向对象的风格

直接使用对象及其方法.

Using the object oriented style

Work with the objects and their methods directly.

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()

这篇关于如何在for循环中使用Matplotlib处理多个图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆