1

I have a while function that generates two lists of numbers and at the end I plot them using matplotlib.pyplot.

I'm doing

while True:
    #....
    plt.plot(list1)
    plt.plot(list2)
    plt.show()

But in order to see the progression I have to close the plot window. Is there a way to refresh it with the new data every x seconds?

2 Answers 2

3

The most robust way to do what you want is to use matplotlib.animation. Here's an example of animating two lines, one representing sine and one representing cosine.

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

fig, ax = plt.subplots()
sin_l, = ax.plot(np.sin(0))
cos_l, = ax.plot(np.cos(0))
ax.set_ylim(-1, 1)
ax.set_xlim(0, 5)
dx = 0.1

def update(i):
    # i is a counter for each frame.
    # We'll increment x by dx each frame.
    x = np.arange(0, i) * dx
    sin_l.set_data(x, np.sin(x))
    cos_l.set_data(x, np.cos(x))
    return sin_l, cos_l

ani = animation.FuncAnimation(fig, update, frames=51, interval=50)
plt.show()

For your particular example, you would get rid of the while True and put the logic inside that while loop in the update function. Then, you just have to make sure to do set_data instead of making a whole new plt.plot call.

More details can be found in this nice blog post, the animation API, or the animation examples.

Sign up to request clarification or add additional context in comments.

Comments

0

I think what you're looking for is the "animation" feature.

Here is an example

This example is a second one.

Comments

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.