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 :(
Download the “Install Matplotlib (for PC). bat” file from my web site, and double-click it to run it. Test your installation. Start IDLE (Python 3.4 GUI – 32 bit), type “import matplotlib”, and confirm that this command completes without an error.
Plotly has several advantages over matplotlib. One of the main advantages is that only a few lines of codes are necessary to create aesthetically pleasing, interactive plots. The interactivity also offers a number of advantages over static matplotlib plots: Saves time when initially exploring your dataset.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With