MarAja
MarAja

Reputation: 1597

Can't update my plot with matplotlib

I am receiving data on my client and I have to plot them dynamically using matplotlib. I want to update my plot continuously. Here is what I tried on a simple example:

import time
import numpy as np
import matplotlib.pyplot as plt

h, = plt.plot([], [])

plt.ion()
plt.show()

for i in range(0, 100):
    t = np.arange(i * 0.05, (i+1) * 0.05, 0.01)
    y = np.sin(2*np.pi*t)
    h.set_xdata(np.append(h.get_xdata(), t))
    h.set_ydata(np.append(h.get_ydata(), t))
    plt.draw()
    time.sleep(0.05)

But nothing is plotting (neither in python2.7 nor 3), if I remove the activation of interactive mode (ion()) then I get an empty plot (show() call) but nothing is updated (the program seems to pause and don't go in the loop).

Can someone help?

Upvotes: 1

Views: 180

Answers (1)

Bart
Bart

Reputation: 10250

Update based on the discussion below: the original code from MarAja is working, the only problem is that the axis limits aren't being updated, so it looks as if the plot isn't being updated.


From this example, it seems that you have to redraw the plot using fig.canvas.draw(). Also note that you either have to set an appropriate xlim and ylim to capture the entire data series, or update them every step (like I did in this example):

import time
import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
h, = plt.plot([], [])

plt.ion()
plt.show() 

for i in range(0, 100):
    t = np.arange(i * 0.05, (i+1) * 0.05, 0.01)
    y = np.sin(2*np.pi*t)
    h.set_xdata(np.append(h.get_xdata(), t))
    h.set_ydata(np.append(h.get_ydata(), t))

    fig.canvas.draw()
    time.sleep(0.05)

    plt.xlim(0,h.get_xdata().max())
    plt.ylim(0,h.get_ydata().max())

Upvotes: 1

Related Questions