如何在程序运行时更新Matplotlib图?
下面的代码
plt.figure(1)
plt.subplot(211)
plt.axis([0,100, 95, 4000])
plt.plot(array1,array2,'r')
plt.ylabel("label")
plt.xlabel("label")
plt.subplot(212)
plt.specgram(array3)
plt.show()
可以生成两个很不错的图表。但是,怎么才能在不关闭窗口的情况下更新这些内容呢?
我需要在一个线程中创建这个窗口,同时在主代码中更新一个变量,而这个窗口也要根据这个变量来更新。
你会怎么做呢?
1 个回答
6
这里有几个选择:
第一个是使用mpl的很棒的示例,具体可以查看这些例子。
第二个是自己写循环,这样你能更好地理解发生了什么。
下面是一个简单的例子,使用pylab.draw()函数,而不是show(),虽然不复杂,但能帮助你理解基本的内容:
import pylab
import time
pylab.ion() # animation on
# Note the comma after line. This is placed here because
# plot returns a list of lines that are drawn.
line, = pylab.plot(0,1,'ro',markersize=6)
pylab.axis([0,1,0,1])
line.set_xdata([1,2,3]) # update the data
line.set_ydata([1,2,3])
pylab.draw() # draw the points again
time.sleep(6)
line1, = pylab.plot([4],[5],'g*',markersize=8)
pylab.draw()
for i in range(10):
line.set_xdata([1,2,3]) # update the data
line.set_ydata([1,2,3])
pylab.draw() # draw the points again
time.sleep(1)
print "done up there"
line2, = pylab.plot(3,2,'b^',markersize=6)
pylab.draw()
time.sleep(20)
希望这对你有帮助。