简体   繁体   中英

Plotting changing graphs with matplotlib

So I have been trying to get a plot to update every iteration through a loop. A stripped down version of my code is as follows:

  1 import matplotlib.pyplot as plt
  2 import numpy as np
  3 
  4 x = np.linspace(0, 9, 10)
  5 for j in range(10):
  6     y = np.random.random(10)
  7     plt.plot(x,y)
  8     plt.show()
  9     plt.pause(1)
 10     plt.clf()

My issue is that I have to close each plot before the next one is created; it seems like the plot is stuck on plt.show(), whereas I expect a new plot to replace the current one every second without needing my interaction. I've consulted the following questions:

When to use cla(), clf() or close() for clearing a plot in matplotlib?

Python plt: close or clear figure does not work

Matplotlib pyplot show() doesn't work once closed

But none of the solutions seemed to work for me. Any help would be appreciated!

You should set interactive mode with plt.ion(), and use draw to update

import matplotlib.pyplot as plt
import numpy as np

plt.ion()
fig=plt.figure()

x = np.linspace(0, 9, 10)
for j in range(10):
    y = np.random.random(10)
    plt.plot(x,y)
    fig.canvas.draw()
    plt.pause(1)
    plt.clf()

link to tutorial

Note that it might not work on all platforms; I tested on Pythonista/ios, which didn't work as expected.

From

matplotlib tutorial

Note Interactive mode works with suitable backends in ipython and in the ordinary python shell, but it does not work in the IDLE IDE. If the default backend does not support interactivity, an interactive backend can be explicitly activated using any of the methods discussed in What is a backend?.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM