1

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?

MarAja
  • 1,547
  • 4
  • 20
  • 36

1 Answers1

1

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())
Community
  • 1
  • 1
Bart
  • 9,825
  • 5
  • 47
  • 73
  • Strange, I still get no plot at all (Python 2.7 or 3). Maybe my code is ok but something behind is broken. – MarAja Nov 12 '15 at 16:56
  • Do normal plots work? I tried this on OS X using Python 3.4.3 – Bart Nov 12 '15 at 17:08
  • Normal plot works fine. Can you try my code above and tell me if it works? – MarAja Nov 12 '15 at 17:12
  • 1
    Sorry, I thought that your original code wasn't working, but that was only because the axis limits weren't being updated. If I add the `plt.xlim(..)` and `plt.ylim(..)` from my example your original version works for me. I'll update my answer (although it isn't really an answer any more....) – Bart Nov 12 '15 at 17:20