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?

1

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

4 Comments

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.
Yup, that is exactly what this is, change one line and delete 2 and it should drop in anywhere.
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 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?

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.