Matplotlib动画打印图形直到循环完成后才响应

2024-06-16 11:50:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试制作一个绘图动画,其中我的两个向量X,Y通过一个循环进行更新。 我正在使用FuncAnimation。我遇到的问题是,在循环完成之前,该图将显示Not Responding或空白

所以在循环过程中,我会得到如下结果:

enter image description here

但如果我停止循环或在循环结束时停止循环,则会出现该图形

enter image description here

我已将我的图形后端设置为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()     

Tags: inimport图形绘图formatplotlibrangeplt
1条回答
网友
1楼 · 发布于 2024-06-16 11:50:01

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

enter image description here

相关问题 更多 >