首页 > 解决方案 > matplotlib - 如何在同一窗口的循环中绘制新图

问题描述

我使用下面的代码。这带来了三个不同的窗口。我希望情节显示在同一个窗口中。有任何想法吗?

谢谢

——ps:澄清。我想先查看 y[0] 与 x[0] 的曲线,然后将其擦除并查看 y[1] 与 x[1],然后擦除并查看 y[2] 与 x[2]。现在它以三种不同的颜色显示所有三个。请参阅第二段代码。

--

import numpy
from matplotlib import pyplot as plt
x = [1, 2, 3]
plt.ion() # turn on interactive mode, non-blocking `show`
for loop in range(0,3):
    y = numpy.dot(x, loop)
    plt.figure()   # create a new figure
    plt.plot(x,y)  # plot the figure
    plt.show()     # show the figure, non-blocking
    _ = input("Press [enter] to continue.") # wait for input from the 



import numpy
import matplotlib.pyplot as plt

%matplotlib notebook

x = [[1, 2, 3], [4,5,6], [7,8,9]]
y = [[1,4,9], [16,25,36], [49,64,81]]

fig, ax = plt.subplots()

plt.ion()
plt.show()
for i in range(3): 
    ax.plot(x[i],y[i])  # plot the figure
    plt.gcf().canvas.draw()
    _ = input("Press [enter] to continue.") # wait for input from the 

标签: matplotlib

解决方案


这应该可以帮助您解决问题。注意在循环外使用 plt.show() 。plt.show()启动一个事件循环,检查当前活动的图形对象,并打开一个显示窗口。

import numpy
%matplotlib notebook
import matplotlib.pyplot as plt

x = [1, 2, 3]
fig, ax = plt.subplots()

plt.ion()
plt.show()
for loop in range(0,3): 
    y = numpy.dot(x, loop)
    line,=ax.plot(x,y)  # plot the figure
    plt.gcf().canvas.draw()
    line.remove()
    del line
    _ = input("Press [enter] to continue.") # wait for input from the 

推荐阅读