带有ion()的MatPlotLib不显示窗口

时间:2019-02-14 19:03:04

标签: python matplotlib

如果我运行以下代码:

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 个答案:

答案 0 :(得分:1)

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

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

相关问题