制作简单的动态图表,用Matplotlib就可以了,Matplotlib中的FuncAnimation类可以通过一个迭代器不断创建图像帧,最后可以通过plt.show,或者直接save,将帧拼成动画保存下来。原理非常简单,博主简单做下记录,没有太多介绍。
前排放个参考链接,里面有更多炫酷的动图制作代码:Animatin-With-Matplotlib
放两个demo吧,一个是动态波浪:
from matplotlib import pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
# initializing a figure in
# which the graph will be plotted
fig = plt.figure()
# marking the x-axis and y-axis
axis = plt.axes(xlim =(0, 4),
ylim =(-2, 2))
# initializing a line variable
line, = axis.plot([], [], lw = 3)
# data which the line will
# contain (x, y)
def init():
line.set_data([], [])
return line,
def animate(i):
x = np.linspace(0, 4, 1000)
# plots a sine graph
y = np.sin(2 * np.pi * (x - 0.01 * i))
line.set_data(x, y)
return line,
anim = FuncAnimation(fig, animate, init_func = init,
frames = 200, interval = 20, blit = True)
anim.save('continuousSineWave.gif', writer = 'PillowWriter', fps = 30)
anim.save('continuousSineWave.mp4', writer = 'ffmpeg', fps = 30)
其中最重要的是FuncAnimation类:
fig,要绘图的窗口
animate,动图绘制的回调函数,每次更新图片都在这个函数里面
frames, 帧数,也可以传入一个可迭代的对象,指定回调函数入参范围
interval,动画间隔时间,单位是ms
blit,是否进行某种动画渲染
如果要保存视频,你需要额外安装ffmpeg,否则你只能保存gif了,保存下来的gif一般比较大,保存下来的视频是这样子的
另外,再放另一个demo,原理也是一样的,只是传入的是一个迭代器
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def update_points(num):
point_ani.set_data(x[num], y[num])
return point_ani,
def update_points_with_text(num):
point_ani.set_data(x[num], y[num])
if num % 5 == 0:
point_ani.set_marker("*")
point_ani.set_markersize(12)
else:
point_ani.set_marker("o")
point_ani.set_markersize(8)
text_pt.set_position((x[num],y[num]))
text_pt.set_text("x=%.3f, y=%.3f"%(x[num],y[num]))
return point_ani,text_pt,
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
fig = plt.figure(tight_layout=True)
plt.plot(x, y)
point_ani, = plt.plot(x[0], y[0], "ro")
plt.grid(ls="--")
text_pt = plt.text(4, 0.8, '', fontsize=16)
ani = animation.FuncAnimation(
fig, update_points_with_text, np.arange(0, 100), interval=100, blit=True)
ani.save('celluloid_legends.gif', writer = 'imagemagick')
plt.show()
另外,如果figure plt 画不了,那么你可以把图用camera.shot一张一张存下来,然后拼成gif动图,这个可以看文章开头的链接,里面那个3D视角切换的例子就是。
OK,See You Next Chapter!