How to update a plot on same figure during the loop? - GeeksforGeeks

01 Jul, 2021
We can use matplotlib to update a plot on every iteration during the loop. With the help of matplotlib.pyplot.draw() function we can update the plot on the same figure during the loop.
Using matplotlib.pyplot.draw(): It is used to update a figure that has been changed. It will redraw the current figure.
Syntax: figure.canvas.draw()
Before this we use figure.ion() function to run a GUI event loop. Without using figure.ion() we may not be able to see the GUI plot.
In the given example firstly we are importing all the necessary libraries that we are going to use. And then creating X and Y. X holds the values from 0 to 10 which evenly spaced into 100 values. e.g. we are creating values from 2 to 3 with evenly spaced 5 values (np.linspace(2, 3, 5)) It should output like these 5 values from 2 to 3 evenly spaced array([2 , 2.25, 2.5 , 2.75, 3 ]). After that we are initializing GUI using plt.ion() function, now we have to create a subplot, so we can plot X and Y values. After that we are running a for loop up to some iterations and creating a new_y values which hold our updating value then we are updating the values of X  and Y using set_xdata() and set_ydata(). And canvas.draw() will plot the updated values and canvas.flush_events() holds the GUI event till the UI events have been processed. This will run till the loop ends and values will be updated continuously.
Code:
Python3
# importing librariesimport numpy as npimport timeimport matplotlib.pyplot as plt # creating initial data values# of x and yx = np.linspace(0, 10, 100)y = np.sin(x) # to run GUI event loopplt.ion() # here we are creating sub plotsfigure, ax = plt.subplots(figsize=(10, 8))line1, = ax.plot(x, y) # setting titleplt.title("Geeks For Geeks", fontsize=20) # setting x-axis label and y-axis labelplt.xlabel("X-axis")plt.ylabel("Y-axis") # Loopfor _ in range(50):    # creating new Y values    new_y = np.sin(x-0.5*_)     # updating data values    line1.set_xdata(x)    line1.set_ydata(new_y)     # drawing updated values    figure.canvas.draw()     # This will run the GUI event    # loop until all UI events    # currently waiting have been processed    figure.canvas.flush_events()     time.sleep(0.1)
Output: 
Updating plot
Here, figure.canvas.flush_events()  is used to clear the old figure before plotting the updated figure.
Example 2: In this example code, we are updating the value of y in a loop using set_xdata() and redrawing the figure every time using canvas.draw().
Python3
from math import piimport matplotlib.pyplot as pltimport numpy as npimport time # generating random data valuesx = np.linspace(1, 1000, 5000)y = np.random.randint(1, 1000, 5000) # enable interactive modeplt.ion() # creating subplot and figurefig = plt.figure()ax = fig.add_subplot(111)line1, = ax.plot(x, y) # setting labelsplt.xlabel("X-axis")plt.ylabel("Y-axis")plt.title("Updating plot...") # loopingfor _ in range(50):       # updating the value of x and y    line1.set_xdata(x*_)    line1.set_ydata(y)     # re-drawing the figure    fig.canvas.draw()         # to flush the GUI events    fig.canvas.flush_events()    time.sleep(0.1)
Output:
Updating plot.
saurabh1990aror
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Convert integer to string in Python