Python 您可以在 matplotlib 中绘制实时数据吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18791722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can you plot live data in matplotlib?
提问by nickponline
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 :(
采纳答案by tacaswell
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.
如果你想走得非常快,你应该研究一下 blitting。
回答by mattexx
f.show()does not block, and you can use drawto update the figure.
f.show()不会阻塞,您可以使用它draw来更新图形。
f = pylab.figure()
f.show()
while True:
time.sleep(1)
pylab.plot(data)
pylab.draw()

