首页 > 解决方案 > Matplotlib 动画图 - 图形在循环完成之前没有响应

问题描述

我正在尝试为我的两个向量 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()     

标签: pythonmatplotlibspyder

解决方案


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()

在此处输入图像描述


推荐阅读