关于python:带有ion()的MatPlotLib不显示窗口

MatPlotLib with ion() does not show window

如果我运行以下代码:

1
2
3
4
5
6
7
8
9
10
11
import matplotlib.pyplot as plt
import numpy as np

#plt.ion()

while True:
    print('loop')
    x = range(10)
    y = np.random.rand(10)
    plt.scatter(x, y)
    plt.show()

然后我在屏幕上看到一个散点图。然后,每次我关闭绘图窗口时,都会显示一个包含新数据的新绘图。

但是,如果我取消注释plt.ion()行,则什么都不会显示。没有创建任何窗口,程序仅继续执行循环,打印出"循环"。

我希望能够显示图形,然后自动返回代码,并且图形仍然显示。我该怎么办?


如果要绘制在同一图形窗口的顶部,而不是每次迭代都生成一个新窗口,则可以使用以下方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
import matplotlib.pyplot as plt
import numpy as np

plt.ion()

fig, ax = plt.subplots(1, 1)

while True:
    # If wanting to see an"animation" of points added, add a pause to allow the plotting to take place
    plt.pause(1)
    x = range(10)
    y = np.random.rand(10)
    ax.scatter(x, y)

您看到的结果将取决于您使用的matplotlib后端。如果要查看正在添加的新点,则应使用Qt4Qt5