Python matplotlib用动画包绘制Line2D对象

时间:2015-09-22 15:20:52

标签: python matplotlib

我正在尝试动画Line2D集的列表,问题是我将plt.plot(xx)附加到数组,因为if then else循环而且我需要这种取消因为我的结果我想要看看。

它工作正常如果我将每个时间步长保存为图形,但它不适用于动画。

也许你可以给我一个提示,这是我的代码:

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)

1 个答案:

答案 0 :(得分:0)

动画线条的方法是调用一系列图形,返回线条对象并使用动画根据新数据更新这些图形。您可以根据需要为多行执行此操作(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生成数据,如果您已有数据,则可以将其用作数组索引。