【问题标题】:Matplotlib animate plot - Figure not responding until loop is doneMatplotlib 动画图 - 图形在循环完成之前没有响应
【发布时间】:2021-07-09 23:27:00
【问题描述】:

我正在尝试为我的两个向量 X,Y 通过循环更新的情节制作动画。 我正在使用FuncAnimation。我遇到的问题是该图将显示Not Responding 或空白,直到循环完成。

所以在循环期间,我会得到类似的东西:

但如果我停止循环或在最后,数字会出现。

我已将我的图形后端设置为automatic

下面是代码示例:

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

def animate( intermediate_values):
    x = [i for i in range(len(intermediate_values))]
    y = intermediate_values 
    plt.cla()
    plt.plot(x,y, label = '...')
    plt.legend(loc = 'upper left')
    plt.tight_layout()        
    
    
x = []
y = []
#plt.ion()
for i in range(50):
    x.append(i)
    y.append(i)
    ani = FuncAnimation(plt.gcf(), animate(y), interval = 50)  
    plt.tight_layout()
    #plt.ioff()
    plt.show()     

【问题讨论】:

    标签: python matplotlib spyder


    【解决方案1】:

    matplotlib中动画的结构是在循环过程中不使用动画函数,而动画函数就是循环过程。设置好初始图形后,动画函数会更新数据。

    import matplotlib.pyplot as plt
    from matplotlib.animation import FuncAnimation
    
    x = []
    y = []
    
    fig = plt.figure()
    ax = plt.axes(xlim=(0,50), ylim=(0, 50))
    line, = ax.plot([], [], 'b-', lw=3, label='...')
    ax.legend(loc='upper left')
    
    
    def animate(i):
        x.append(i)
        y.append(i)
        line.set_data(x, y)
        return line,
    
    ani = FuncAnimation(fig, animate, frames=50, interval=50, repeat=False)
    
    plt.show()
    

    【讨论】:

    • 官方参考可以找到here。如果我的回答对你有帮助,请考虑采纳为正确答案
    猜你喜欢
    • 2017-01-31
    • 1970-01-01
    • 2018-02-08
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多