简体   繁体   中英

Multiple lines animation in matplotlib

I want to animate lines on a matplolib figure like this:

线条动画

Only the horizontal lines interest me.

I made a function which animates one line like in the model above:

def animate(i):
    line.set_ydata(0 - np.exp(i/20))
    return line,

line, = ax.plot((-100, 100), (0,0), 'r', lw=1)

ani = animation.FuncAnimation(fig, animate, frames=np.linspace(0, 78, 79), blit=True, interval=20,
repeat=True)

Now the problem is that I need ten of these animations with a line shift. I tried several things like creating one function per line, creating 10 lines, putting an init function in "ani", but nothing works because I don't know enough about how animations work.

The main point of this animation is to get the spacing right for the illusion of continuity. I tried to keep your structure unchanged as much as possible.

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

#hey, it's in CinemaScope   
fig, ax = plt.subplots(figsize=(11.75, 5))
xrange = (-100, 100)
numb_of_lines = 8
frames = 30
scal_fac = 50
#define the y-range, so that the last line disappears outside the frame
#also set the upper range in a ratio that is used in photography to evoke a pleasant image composition 
yrange = (-0.99 * np.exp(frames * numb_of_lines/scal_fac), np.exp(frames * numb_of_lines /scal_fac)/2)
ax.set_xlim(xrange)
ax.set_ylim(yrange)
ax.set_xticks([])
ax.set_yticks([])

#set unchanging horizon line to improve the illusion of continuity
ax.plot(xrange, (-1,-1), 'r', lw=1)

#set initial lines
line_coll = []
for j in range(numb_of_lines):
    line,  = ax.plot(xrange, (-np.exp(frames * j/scal_fac),-np.exp(frames * j/scal_fac)), 'r', lw=1)
    line_coll.append(line)    

def animate(i):   
    for j in range(numb_of_lines):
        line_coll[j].set_ydata(-np.exp((i + j * frames)/scal_fac)) 
    return line_coll  
    
ani = anim.FuncAnimation(fig, animate, frames=frames, blit=True, repeat=True, interval=20)
plt.show()

Output:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM