且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

对具有不同颜色的线进行动画处理

更新时间:2023-01-27 09:14:19

要绘制其属性沿其变化的线,请使用LineCollection.示例此处例子.

To plot a line whose properties change along it, use a LineCollection. Example here and here. To make an animation with a LineCollection, see this example.

要回答事物在上面的代码中的工作方式,请在animate()中用line.set_data(x, y)重置行x,y属性.然后该函数将Matplotlib必须在每一帧更新的艺术家集合(line,)返回给Matplotlib.

To answer how the thing works in the code above, within animate() you are resetting the line x,y properties with line.set_data(x, y). the function then returns to Matplotlib the set (line,) of artists that matplotlib must update at each frame.

这就是我在寻找的内容(仅当您的平台在上次通话中支持blit=true时才启用它):

Here's what I think you're looking for (enable blit=true only if your platform supports it in the last call):

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))

cmap = ListedColormap(['b', 'r', 'b'])
norm = BoundaryNorm([0, 1, 1.5, 2], cmap.N)

line = LineCollection([], cmap=cmap, norm=norm,lw=2)
line.set_array(np.linspace(0, 2, 1000))
ax.add_collection(line)

# initialization function: plot the background of each frame
def init():
    line.set_segments([])
    return line,

# animation function.  This is called sequentially
def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    points = np.array([x, y]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)
    line.set_segments(segments)
    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                           frames=200, interval=20)