Mat*_*lem 3 python animation matplotlib
我正在尝试为演示文稿制作动画数据。我正在尝试使用 python 的动画包来做到这一点。我想要做的大致归结为http://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/ 中的第一个例子
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
# 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))
line, = ax.plot([], [], lw=2)
# initialization function: plot the background of each frame
def init():
line.set_data([], [])
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))
line.set_data(x, y)
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, blit=True)
Run Code Online (Sandbox Code Playgroud)
我是 python 的新手,所以我正在努力理解正在发生的事情。对我来说,似乎 init() 和 animate(i) 都没有修改它们返回的内容。此外,他们正在修改的对象 line(而不是 line,)之前尚未声明。
无论哪种方式,我想要做的是获得数据,在这种情况下是正弦波,分段着色。0 和 1 之间的蓝色,1 和 1.5 之间的红色,1.5 和 2 之间的蓝色。我尝试了很多东西,但无法使其正常工作。我尝试让这些函数返回整个图形,而不仅仅是线,希望它们能刷新预览图形并绘制我绘制的复合线,但无济于事。
在这个框架中,我如何为一条由(不同颜色的)线组成的线设置动画?
要绘制属性沿其变化的线,请使用 LineCollection。这里和这里的例子。要使用 LineCollection 制作动画,请参阅此示例。
为了回答上面代码中的事情是如何工作的,animate()您正在x,y使用line.set_data(x, y). 然后,该函数将(line,)matplotlib 必须在每一帧更新的艺术家集返回给 Matplotlib 。
这是我认为您正在寻找的内容(blit=true仅当您的平台在最后一次调用中支持时才启用):
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)
Run Code Online (Sandbox Code Playgroud)
