Matplotlib图仅在窗口关闭时更新?

时间:2016-11-13 01:04:00

标签: python animation matplotlib graph graphics

我编写了以下脚本来显示简单的正弦曲线以无限更新广告:

#!/usr/bin/env python
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
from math import sin
n = 0
As =[]
Ns = []
def animate(i):
    As.append(sin(n))
    Ns.append(n)
    ax1.plot(np.array(Ns),np.array(As))

while True:
    fig1 = plt.figure()
    ax1 = fig1.add_subplot(1,1,1)
    ani1 = animation.FuncAnimation(fig1, animate, interval=1)
    n = n + 0.05
    plt.show()

然而,当我尝试关闭窗口时,该行只会更新(如在更改形状中),我找不到任何可以解决此问题的方法 - 它将如何完成?非常感谢提前。

1 个答案:

答案 0 :(得分:0)

您必须在n内更改animate以添加不同的点 - 现在您总是添加相同的点,这样您就不会看到差异。在代码中print(Ns)内尝试animate

import matplotlib.pyplot as plt
import matplotlib.animation as animation
from math import sin

n = 0
As = []
Ns = []

# -----

def animate(i):
    global n

    Ns.append(n)
    As.append(sin(n))
    ax1.plot(Ns, As)

    n += 0.05

# -----

fig1 = plt.figure()
ax1 = fig1.add_subplot(1,1,1)
ani1 = animation.FuncAnimation(fig1, animate, interval=1)
plt.show()

BTW:您可以使用i

def animate(i):

    n = 0.05 * i

    Ns.append(n)
    As.append(sin(n))
    ax1.plot(Ns, As)