Python 在使用Matplotlib的每个循环期间,我是否可以生成并显示不同的图像?
我不熟悉Matplotlib和Python。我主要使用Matlab。目前,我正在使用一个Python代码来运行循环。在每个循环中,我将进行一些数据处理,然后根据处理后的数据显示一幅图像。当我转到下一个循环时,我希望关闭以前存储的图像,并根据最新数据生成新图像 换句话说,我需要一个与以下Matlab代码等效的python代码:Python 在使用Matplotlib的每个循环期间,我是否可以生成并显示不同的图像?,python,matlab,matplotlib,Python,Matlab,Matplotlib,我不熟悉Matplotlib和Python。我主要使用Matlab。目前,我正在使用一个Python代码来运行循环。在每个循环中,我将进行一些数据处理,然后根据处理后的数据显示一幅图像。当我转到下一个循环时,我希望关闭以前存储的图像,并根据最新数据生成新图像 换句话说,我需要一个与以下Matlab代码等效的python代码: x = [1 2 3]; for loop = 1:3 close all; y = loop * x; figure(1); p
x = [1 2 3];
for loop = 1:3
close all;
y = loop * x;
figure(1);
plot(x,y)
pause(2)
end
import numpy
import time
from matplotlib import pyplot as plt
if __name__ == '__main__':
x = [1, 2, 3]
plt.ion()
for loop in xrange(1, 4):
y = numpy.dot(loop, x)
plt.close()
plt.figure()
plt.plot(x,y)
plt.draw()
time.sleep(2)
我尝试了以下python代码来实现我的目标:
import numpy as np
import matplotlib
import matplotlib.lib as plt
from array import array
from time import sleep
if __name__ == '__main__':
x = [1, 2, 3]
for loop in range(0,3):
y = numpy.dot(x,loop)
plt.plot(x,y)
plt.waitforbuttonpress
plt.show()
此代码将所有绘图叠加在同一个图中。如果我将plt.show()
命令放入for循环中,则只显示第一个图像。因此,我无法用Python复制我的Matlab代码。尝试以下方法:
import numpy
from matplotlib import pyplot as plt
if __name__ == '__main__':
x = [1, 2, 3]
plt.ion() # turn on interactive mode
for loop in range(0,3):
y = numpy.dot(x, loop)
plt.figure()
plt.plot(x,y)
plt.show()
_ = input("Press [enter] to continue.")
如果要关闭上一个绘图,请在显示下一个绘图之前:
import numpy
from matplotlib import pyplot as plt
if __name__ == '__main__':
x = [1, 2, 3]
plt.ion() # turn on interactive mode, non-blocking `show`
for loop in range(0,3):
y = numpy.dot(x, loop)
plt.figure() # create a new figure
plt.plot(x,y) # plot the figure
plt.show() # show the figure, non-blocking
_ = input("Press [enter] to continue.") # wait for input from the user
plt.close() # close the figure to show the next one.
plt.ion()
这是matlab代码的副本:
x = [1 2 3];
for loop = 1:3
close all;
y = loop * x;
figure(1);
plot(x,y)
pause(2)
end
import numpy
import time
from matplotlib import pyplot as plt
if __name__ == '__main__':
x = [1, 2, 3]
plt.ion()
for loop in xrange(1, 4):
y = numpy.dot(loop, x)
plt.close()
plt.figure()
plt.plot(x,y)
plt.draw()
time.sleep(2)
无需将原始输入的返回值
分配给名为\uu
的变量。如果你不打算使用这个值,你可以在一行上自己做raw\u input(“blah”)
。是的,我很清楚,这就是为什么我这么做的原因,所以当你复制并粘贴到终端上时,它不会打印任何raw\u input返回的内容,然后大多数plt命令返回对象。。。因此,这取决于用户,无论哪种方式,我都翻译了他的原始matlab代码,如果我理解正确的话……非常感谢,@samy.vilar。它完全符合我的需要!我真的很感谢你的帮助。谢谢@BrenBarn的宝贵评论。