0

I would like to update the y-data in my 2 D plot without having to call 'plot' everytime

from matplotlib.figure import Figure
fig = Figure(figsize=(12,8), dpi=100) 

for num in range(500):
   if num == 0:
     fig1 = fig.add_subplot(111)
     fig1.plot(x_data, y_data)
     fig1.set_title("Some Plot")
     fig1.set_ylabel("Amplitude")
     fig1.set_xlabel("Time")

  else:
     #fig1 clear y data
     #Put here something like fig1.set_ydata(new_y_data), except that fig1 doesnt have set_ydata attribute`

I could clear and plot 500 times, but it would slow down the loop. Any other alternative?

jrjc
  • 21,103
  • 9
  • 64
  • 78
jenkris
  • 1
  • 1
  • also see http://stackoverflow.com/questions/12822762/pylab-ion-in-python-2-matplotlib-1-1-1-and-updating-of-the-plot-while-the-pro/12826273#12826273 – tacaswell Nov 06 '14 at 14:28

1 Answers1

1

See http://matplotlib.org/faq/usage_faq.html#parts-of-a-figure for the description of the parts of an mpl figure.

If you are trying to create an animation, take a look at the matplotlib.animation module which takes care of most of the details for you.

You are creating the Figure object directly, so I am assuming that you know what you are doing and are taking care of the canvas creation elsewhere, but for this example will use the pyplot interface to create the figure/axes

import matplotlib.pyplot as plt

# get the figure and axes objects, pyplot take care of the cavas creation
fig, ax = plt.subplots(1, 1)  # <- change this line to get your axes object differently
# get a line artist, the comma matters
ln, = ax.plot([], [])
# set the axes labels
ax.set_title('title')
ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')

# loop over something that yields data
for x, y in data_source_iterator:
   # set the data on the line artist
   ln.set_data(x, y)
   # force the canvas to redraw
   ax.figure.canvas.draw()  # <- drop this line if something else manages re-drawing
   # pause to make sure the gui has a chance to re-draw the screen
   plt.pause(.1) # <-. drop this line to not pause your gui
tacaswell
  • 84,579
  • 22
  • 210
  • 199
  • The sample code I gave here is a part of a large code, which uses matplotlib.figure along with tkinter canvas for several different type of plots. I am searching for a solution using matplotlib.figure, so that i wont have to edit the whole code. I am trying to plot real time data and 500 iterations of 'plot' slows down the loop. – jenkris Nov 06 '14 at 15:00
  • Yup, that is exactly what this is, change one line and delete 2 and it should drop in anywhere. – tacaswell Nov 06 '14 at 15:01
  • It works.Tiny problem, what if its multiple dataset on y-axis for a single plot eg. (x, y1) (x,y2) (x,y3)..It gives error 'too many values to unpack' – jenkris Nov 06 '14 at 15:56
  • @jenkris I am going to engage in some socratic method here. What does `ax.plot` return? What is the comma on the left hand side of the expression doing? – tacaswell Nov 07 '14 at 13:53