How to update a plot in Matplotlib

In this post, we will see how we update a plot in Matplotlib. In matplotlib, updating a plot means erasing all the previous data and entering new data. This process goes in a loop. We have already discussed plotting in Matplotlib. We now just have to erase the previous data and enter new data and the same thing is in the loop.

Importing Libraries:

import matplotlib.pyplot as plt
import numpy as np

After importing all the necessary libraries, we will now plot a graph using the following code.

x = np.linspace(0, 20*np.pi, 100)
y = np.cos(x)

Now we will turn On the interactive plot using plt.ion(). To turn off the interactive plot we use plt.ioff().

Now let us construct the graph using the following code:

figure = plt.figure()
ax = figure.add_subplot(111)
line_of_graph, = ax.plot(x, y, 'r-')

After the construction of the code, we want the code to work on a loop. We will use the For loop for the action.

for phase in np.linspace(0, 20*np.pi, 100):
  line_of_graph.set_ydata(np.cos(0.5 * x + phase))
  figure.canvas.draw()
  figure.canvas.flush_events()

The variable x represents the x-axis. The y variable represents the y-axis. Take the cosine graph, for instance.

The figure.canvas.draw() method in python allows us to redraw the same figure.

The figure.canvas.flush_events() method creates a new figure.

The complete code To update the plot in Matplotlib:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 20*np.pi, 100)
y = np.cos(x)

plt.ion()
figure = plt.figure()
ax = figure.add_subplot(111)
line_of_graph, = ax.plot(x, y, 'r-')

for phase in np.linspace(0, 20*np.pi, 100):
  line_of_graph.set_ydata(np.cos(0.5 * x + phase))
  figure.canvas.draw()
  figure.canvas.flush_events()

Output:

How to update a plot in Matplotlib

The output will be in a loop and the graph will vary according to the inputs taken by the user.

With this, we have concluded our tutorial. Learn, to create a pie chart using the Matplotlib library in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *