dba
dba

Reputation: 345

Plot incoming stream of numbers with matplotlib

I want to plot an incoming stream of numbers as a real-time graph. currently, all it does, is to show a gray figure-window with no content. The data gets printed to the terminal as I expect it.

import socket
import matplotlib as m
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
from matplotlib import style

style.use('fivethirtyeight')

fig = plt.figure()
plt.axis([0,10,0,1])
plt.ion()


samples = 15*200

channels = [np.linspace(start= 0, stop = 0,num = samples)]

def animate():
    plt.plot(range(0,samples),channels[0])
    plt.draw()


UDP_IP = "127.0.0.1"
UDP_PORT = 8888
sock = socket.socket(socket.AF_INET, # Internet
                     socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))

k = 0
while True:
    data, addr = sock.recvfrom(2048) # buffer size is 1024 bytes      
    # write data to channel
    channels[0][k % samples] = eval(data)[0]
    animate()
    print channels[0][k % samples]

Upvotes: 1

Views: 1853

Answers (2)

Bennett Brown
Bennett Brown

Reputation: 5383

Does it resolve the problem if instead of plt.draw(), you call fig.canvas.draw()? The method for updating belongs to the canvas object. Using the state-based interface of pyplot makes it less clear which object is being referenced, and you might prefer the OO interface. Especially because you are retaining the reference to fig, you might as well call it explicitly.

Upvotes: 1

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339340

Replace plt.draw() by plt.pause(t), with t being the time to wait between frames (it should not be 0). This ensures that the figure actually gets time to update and the GUI can process any events.

Upvotes: 1

Related Questions