您可以在matplotlib中绘制实时数据吗? [英] Can you plot live data in matplotlib?
本文介绍了您可以在matplotlib中绘制实时数据吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在从一个线程中的套接字读取数据,并希望随着新数据的到来绘制和更新绘制.我编写了一个小的原型来模拟事物,但是没有用:
I'm reading data from a socket in one thread and would like to plot and update the plot as new data arrives. I coded up a small prototype to simulate things but it doesn't work:
import pylab
import time
import threading
import random
data = []
# This just simulates reading from a socket.
def data_listener():
while True:
time.sleep(1)
data.append(random.random())
if __name__ == '__main__':
thread = threading.Thread(target=data_listener)
thread.daemon = True
thread.start()
pylab.figure()
while True:
time.sleep(1)
pylab.plot(data)
pylab.show() # This blocks :(
推荐答案
import matplotlib.pyplot as plt
import time
import threading
import random
data = []
# This just simulates reading from a socket.
def data_listener():
while True:
time.sleep(1)
data.append(random.random())
if __name__ == '__main__':
thread = threading.Thread(target=data_listener)
thread.daemon = True
thread.start()
#
# initialize figure
plt.figure()
ln, = plt.plot([])
plt.ion()
plt.show()
while True:
plt.pause(1)
ln.set_xdata(range(len(data)))
ln.set_ydata(data)
plt.draw()
如果您想快点走,应该研究一下发条.
If you want to go really fast, you should look into blitting.
这篇关于您可以在matplotlib中绘制实时数据吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文