【问题标题】:Matplotlib plot only updates when windows is closed?Matplotlib 绘图仅在关闭窗口时更新?
【发布时间】:2016-11-13 01:03:59
【问题描述】:

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

#!/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()

但是,当我尝试关闭窗口时,这条线只会更新(就像完全改变形状一样),我找不到任何东西来解决这个问题 - 该怎么做?非常感谢。

【问题讨论】:

    标签: python animation matplotlib graph graphics


    【解决方案1】:

    您必须在 animate 中更改 n 以添加不同的点 - 现在您始终添加相同的点,因此您看不到差异。在您的代码中尝试 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()
    

    顺便说一句:你可以使用i

    def animate(i):
    
        n = 0.05 * i
    
        Ns.append(n)
        As.append(sin(n))
        ax1.plot(Ns, As)
    

    【讨论】:

    • 谢谢,这真的很有效 - spherical n 行有什么作用?
    • 在您修改后的代码中def animate(i) 行之后?
    猜你喜欢
    • 2016-03-10
    • 1970-01-01
    • 2020-10-26
    • 2014-06-20
    • 1970-01-01
    • 2019-02-22
    • 2014-11-08
    • 2014-01-19
    • 2013-07-23
    相关资源
    最近更新 更多