1

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]
1
  • Why bind channels to a list of a single list? Remove the [ ] around np.linspace and remove the [0] on each reference for cleaner code. Commented Feb 17, 2018 at 22:12

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

3 Comments

plt.draw() does the same as plt.gcf().canvas.draw_idle(); hence if one doesn't work, the other wouldn't either. If you are interested in a solution, read my answer.
OP marked solved. so must be ImportanceOfBeingEarnest. But I don't think those calls are quite the same and could be useful for troubleshooting. The OP assigns the disred Figure object to fig, and calling its draw method is conceivably different than plt.gcf().canvas.draw_idle. Maybe OP has intervening code setting the current figure to something else. Maybe the backend being used by OP is not calling draw because the UI state is not idle for some reason. matplotlib.org/api/…
plt.draw() does the same as plt.gcf().canvas.draw_idle(). fig.canvas.draw() is different, as it does not draw the current figure, but the figure fig. But since there is only one figure in the code, this is then again the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.