背景图

使用matplotlib快捷地创建gif文件

效果

我们想达到的效果就如上图所示。

问题

如果你使用Google搜索怎么使用Matplotlib创建动图,你可能会搜到下面的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
fig, ax = plt.subplots()

x = np.arange(0, 2*np.pi, 0.01)
line, = ax.plot(x, np.sin(x))

def animate(i):
line.set_ydata(np.sin(x + i/10.0)) # update the data
return line,

# Init only required for blitting to give a clean slate.
def init():
line.set_ydata(np.ma.array(x, mask=True))
return line,

ani = animation.FuncAnimation(fig, animate, np.arange(1, 200), init_func=init, interval=25, blit=True)

逻辑是在init方法中使用set_ydata的这类函数;但这个对于我来说略显复杂。所以我想了一个不同的解决方法。

简单实现

方法是构建图片数组,然后将其转化成gif。你需要Imageio这个类库。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import imageio

def plot_for_offset(power, y_max):
# Data for plotting
t = np.arange(0.0, 100, 1)
s = t**power

fig, ax = plt.subplots(figsize=(10,5))
ax.plot(t, s)
ax.grid()
ax.set(xlabel='X', ylabel='x^{}'.format(power),
title='Powers of x')

# IMPORTANT ANIMATION CODE HERE
# Used to keep the limits constant
ax.set_ylim(0, y_max)

# Used to return the plot as an image rray
fig.canvas.draw() # draw the canvas, cache the renderer
image = np.frombuffer(fig.canvas.tostring_rgb(), dtype='uint8')
image = image.reshape(fig.canvas.get_width_height()[::-1] + (3,))

return image

kwargs_write = {'fps':1.0, 'quantizer':'nq'}
imageio.mimsave('./powers.gif', [plot_for_offset(i/4, 100) for i in range(10)], fps=1)

参考:https://blog.csdn.net/monotonomo/article/details/80586194

0%