Python matplotlib用动画包打印Line2D对象

2024-09-28 21:27:00 发布

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

我正在尝试制作一个Line2D集合列表的动画,问题是我正在附加plt.绘图(xx)由于一个if-then-else循环而导致的数组,并且由于我想查看的结果,我需要这种分离。在

如果我把每一个时间步都保存为figure,效果很好,但是对于动画来说就不行了。在

也许你能给我个提示,这是我的代码:

fig2=plt.figure()      
for t in range(nt+1):
    print('Calculating Timestep '+str(t))
    flowfield=u[:,:,t]
    for i in (x_indices):            
        for j in (y_indices):                    
            if flowfield[i,j]==trigs_n:
               frame_sensor=plt.plot(i, j,'r*' ,c='r',marker='s',markersize=5,label='1')
            elif flowfield[i,j]>=trigs_p:                 
               frame_sensor=plt.plot(i, j, 'g*' ,c='g',marker='s',markersize=5,label='1')
            else:
               frame_sensor=plt.plot(i, j,'k*',markerfacecolor='white',markeredgecolor='white',marker='s',markersize=5,label='0')

    frames_sensor.append([frame_sensor])

anim = animation.ArtistAnimation(fig2,frames_sensor,interval=50,blit=True)

Tags: inforifplot动画pltsensorframe
1条回答
网友
1楼 · 发布于 2024-09-28 21:27:00

制作线条动画的方法是调用一系列绘图,返回线条对象并使用animate根据新数据更新这些对象。您可以对任意多行执行此操作(if语句没有影响)。作为基于if条件设置多条线动画的最小示例

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

def init():
    l1, = plt.plot([], [], 'r*-')
    l2, = plt.plot([], [], 'b*-')
    l3, = plt.plot([], [], 'g*-')

    return l1, l2, l3

def update_line(num):
    #Setup some dummy data based on num
    x = np.linspace(0, 2, 100)

    #Some if then else condition to decide which line to update
    if num%3:
        y1 = np.sin(2 * np.pi * (x - 0.01 * num))
        l1.set_data(x, y1)
    elif num%2:
        y2 = np.sin(2 * np.pi * (x - 0.01 * num*0.2))
        l2.set_data(x, y2)
    else:
        y3 = np.sin(2 * np.pi * (x - 0.01 * num*0.3))
        l3.set_data(x,y3)

    return l1, l2, l3

#setup figure
fig1 = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))

#Setup three different line objects
l1, = plt.plot([], [], 'r*-')
l2, = plt.plot([], [], 'b*-')
l3, = plt.plot([], [], 'g*-')

#Animate calls update line with num incremented by one each time
line_ani = animation.FuncAnimation(fig1, update_line, init_func=init,
                                    interval=50, blit=True)

plt.show()

这将基于当前动画迭代num生成数据,如果已经有数据,可以将其用作数组索引。在

相关问题 更多 >