Categories
Python Answers

How to plot in real-time in a while loop using Python matplotlib?

Spread the love

Sometimes, we want to plot in real-time in a while loop using Python matplotlib.

In this article, we’ll look at how to plot in real-time in a while loop using Python matplotlib.

How to plot in real-time in a while loop using Python matplotlib?

To plot in real-time in a while loop using Python matplotlib, we can create a loop to plot the data and then call pause.

For instance, we write

import numpy as np
import matplotlib.pyplot as plt

plt.axis([0, 10, 0, 1])

for i in range(10):
    y = np.random.random()
    plt.scatter(i, y)
    plt.pause(0.05)

plt.show()

to call scatter to plot a scatterplot.

Then we call pause to draw the new data and run the GUI’s `event loop.

And then we call show to show the GUI.

Conclusion

To plot in real-time in a while loop using Python matplotlib, we can create a loop to plot the data and then call pause.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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