Matplotlib update plot in loop

In this Python Matplotlib tutorial, we will discuss the Matplotlib update plot in loop. Here we will cover different examples related to update plot in loop using matplotlib. And we will also cover the following topics:

  • Matplotlib update plot in loop
  • Matplotlib update plot in jupyter
  • Matplotlib update scatter plot in loop
  • Matplotlib update plot in while loop
  • Matplotlib update plot in for loop

Matplotlib update plot in loop

To update the plot on every iteration during the loop, we can use matplotlib. We constantly update the variables to be plotted by iterating in a loop and then plotting the changed values in Matplotlib to plot data in real-time or make an animation.

We use a variety of approaches to visualize the updated plot in real-time through animation, such as:

  • canvas.draw() with canvas_flush_events() function
  • FuncAnimation() function

canvas.draw with canvas_flush_events() function

By updating the variables, we can update the plot in the loop and then display updates through animations using canvas.draw() function.

Example:

# Interactive Mode

%matplotlib notebook

# Import Library


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

# Create subplots

figure, ax = plt.subplots(figsize=(4,5))

# Data Coordinates

x = np.linspace(0, 20, 80)
y = np.sin(x)

# GUI

plt.ion()

#  Plot

plot1, = ax.plot(x, y)

# Labels

plt.xlabel("X-Axis",fontsize=18)
plt.ylabel("Y-Axis",fontsize=18)

for value in range(150):
    update_y_value = np.sin(x-2.5*value)
    
    plot1.set_xdata(x)
    plot1.set_ydata(update_y_value)
    
    figure.canvas.draw()
    figure.canvas.flush_events()
    time.sleep(0.1)


# Display

plt.show()

Explanation:

  • Firstly, turn on the interactive mode.
  • Next, import libraries such as numpy, time, and matplotlib.pyplot.
  • Create subplot by using subplots() function.
  • Next define data coordinate, using linespace() and sin() function.
  • To update the plot with x and y values, we use ion() function.
  • To plot the line, we use plot() function.
  • To define labels, we use xlabel() and ylabel() function.
  • Then we update the variables x and y with set_xdate() and set_ydata() function.
  • To display updates, we use canvas.draw() function.
  • To get the new figure, we use canvas.flush_event()

Output:

Matplotlib update plot in loop example
Matplotlib update plot in loop example-1

FuncAnimation() function

Here we’ll learn to update a plot by updating the variables and displaying them by using the animation function.

The following is the syntax:

matplotlib.animation.FuncAnimation(fig, func, frames=None, 
                                   init_func=None, 
                                   fargs=None, 
                                   save_count=None, * ,    
                                   cache_frame_data=True, 
                                   **kwargs)

Example:

# Import Library

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

# Create figure and subplot

figure, ax = plt.subplots(figsize=(4,3))

x = []
y = []

# Plot

plot_1, = ax.plot(x, y)
plt.axis([0, 30, -2, 2])

# Animation Function

def animate_plot (i):
    x = np.linspace(0, 30, 100)
    y = np.tan(6 * (x - 0.3 * i))
    plot_1.set_data(x, y)
    return plot_1,

# Animated Function

ani = FuncAnimation(figure,
                    animate_plot,
                    frames=3,
                    interval=100)

# Save as gif

ani.save('animation.gif', fps=10)

# Display

plt.show()

Explanation:

  • Import libraries such as numpy, matplotlib.pyplot, and animation.
  • Next, we use the figure() function to plot will be updated.
  • To plot the line chart, we use the plot() function.
  • To set the axes, we use the axis() function.
  • Define data coordinates, using linespace() and tan() function of numpy.
  • The function to be called at each frame is animate_plot. Its first argument is derived from the next value frames.
  • The FuncAnimation() function is used to animate the plot.
  • To save the plot in gif plot, we use save() function.
animation
Matplotlib update plot in loop example-2

Also, check: Matplotlib Pie Chart Tutorial

Matplotlib update plot in Jupyter

We’ll learn to update the plot in Jupyter. For this, we have to import display and clear_output. Now we have two different ways to update our plots, let’s see one by one:

  • clear axes befor plotting
  • without clearing axes before plotting

Clear axes befor plotting

Here we update the plot in Jupyter, and in this approach, we clear the axes before plotting the graph.

Example:

# Import Libraries

import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display, clear_output

# Create figure and subplot

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1) 

# Define and update plot

for i in range(20):
    x = np.linspace(0, i, 100);
    y = np.cos(x) 
    ax.set_xlim(0, i)    
    ax.cla()
    ax.plot(x, y)
    display(fig)    
    clear_output(wait = True)
    plt.pause(0.1)
  • Firstly, import numpy, matplotlib.pyplot, display and clear_output libraries.
  • After this, we create figure and subplot, using figure() and add_subplot() functions.
  • Next, define data coordinates, using linspace() and cos() function.
  • To set the limits, we use set_xlim() function.
  • To plot the graph, we use plot() function.
  • To clear the screen, we use cla() function.
  • To display the figure, display() function.
  • To clear the output, we use clear_output() function.
  • To pause the execution of code, we use pause() function.

Output:

matplotlib update plot in jupyter example-1
matplotlib update plot in jupyter example-1

Without clearing axes before plotting

Here we update the plot in Jupyter, and in this approach, we plot the graph without clearing the axes before the graph.

Example:

# Import Libraries

import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display, clear_output

# Create figure and subplot

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1) 

# Define and update plot

for i in range(100):
    ax.set_xlim(0, 50)
    ax.plot(i, 2, marker='o')
    display(fig)    
    clear_output(wait = True)
    plt.pause(0.2)
  • Import numpy, matplotlib.pyplot, display and clear_output libraries.
  • After this, we create figure and subplot, using figure() and add_subplot() functions.
  • Next, define data coordinates, using linspace() and cos() function.
  • To set the limits, we use set_xlim() function.
  • To plot the graph, we use plot() function.
  • To display the figure, display() function.To clear the output, we use clear_output() function.
  • To pause the execution of code, we use pause() function.

Output:

matplotlib update plot in jupyter example-2
matplotlib update plot in jupyter example-2

Read: Matplotlib multiple bar chart

Matplotlib update scatter plot in loop

Here we’ll learn to update the scatter plots. For this, we can update the values of x and y and add scatter points in each iteration.

Example:

# Import Libraries


import numpy as np

import matplotlib.pyplot as plt

# Create Scatter Plot


x=0
for i in range(40):

    x=np.sin(i)
    y = np.cos(30*x-5)

    plt.scatter(x, y)

    plt.title("Scatter Plot")

    plt.xlabel("X-Axis")
    plt.ylabel("Y-Axis")

    plt.pause(0.2)

# Display

plt.show()
  • Firstly, we import libraries such as numpy and matplotlib.
  • Next, we create a scatter plot using range() and scatter() function.
  • To add a title, we use the title() function.
  • To add axes labels, we use the xlable() and ylabel() functions.
  • To pause the execution, we use the pause() function.
  • To display the graph, we use the show() function.

Output:

Matplotlib update scattter plot in loop example
Matplotlib update scattter plot in loop example

Read: Matplotlib 3D scatter

Matplotlib update plot in while loop

Here we’ll see an example where we create a plot and update its x and y coordinates at each iteration by using the while loop.

The syntax is given below:

while test_expression:
    Body of while

Example:

# Import Libraries

import matplotlib.pyplot as plt
import numpy as np

# GUI

plt.ion()

# Create figure

fig=plt.figure()

# Define Data

data=0
x=list()
y=list()

# While loop

while data <50:
    new_y=np.random.random();
    x.append(data);
    y.append(new_y);
    plt.scatter(data,new_y,marker='*');
    data+=1;
    plt.show()
    plt.pause(0.1) 

Output:

Matplotlib update plot in while loop example
Matplotlib update plot in while loop example

Read: Matplotlib plot bar chart

Matplotlib update plot in for loop

Here we’ll see an example where we create a plot and update its x and y coordinates at each iteration by using for loop.

The syntax is given below:

for val in sequence:
    loop body

Example:

# Import Library
  
import matplotlib.pyplot as plt
import numpy as np

# For loop

for n in range(5):
    x = np.linspace(0,10)
    y = np.sin( x+n )
    plt.scatter( x, y )
    plt.pause(0.5) 

# Display


plt.show()
  • Import matplotlib.pyplot and numpy libraries.
  • Next, use range(), linespace(), and sin() functions to define data coordinates.
  • To plot the graph, we use the scatter() function.

Output:

Matplotlib update plot in for loop example
Matplotlib update plot in for loop example

You may also like to read the following tutorials on Matplotlib.

So, in this Python tutorial, we have discussed the “Matplotlib update plot in loop” and we have also covered some examples related to it. These are the following topics that we have discussed in this tutorial.

  • Matplotlib update plot in loop
  • Matplotlib update plot in jupyter
  • Matplotlib update scatter plot in loop
  • Matplotlib update plot in while loop
  • Matplotlib update plot in for loop