Python实践:画个动图玩玩,Python绘制GIF图总结
文章目录
- Python实践:画个动图玩玩,Python绘制GIF图总结
-
- 具体实现
- Python代码
- 参考资料
上期博客《
Python实践:Pyplot绘图超简洁核心总结》,分享了Python绘图核心方法的体系化总结。
这期分享Python动图制作,可视化绘制动态图,主要用于分析数据的动态变化规律,非常好使,开干。
具体实现
功能需求
- 输入:不同时刻的一维数据,也即二维数据
- 过程:绘制每张图,并存入list
- 输出:一张gif图
实现思路
- 得到要绘制的不同帧横纵坐标轴数据
- 设立好图幅:坐标系、标题、标签等
- 绘制每张图,并用imageio存入list中
- 绘制完毕,将list中的每帧img,输出成gif
Python代码
demo代码如下:
import matplotlib
matplotlib.use('Agg') # 只绘图保存,不显示图片,一定要加在import后面
import matplotlib.pyplot as plt
import numpy as np
import imageio
def generate_gif_1(data, output_path):
image_list = []
ndata = np.array(data)
row, col = ndata.shape
x = range(col)
for i in range(row):
# plot curves
# plt.figure(i)
plt.clf() # 清除上一幅图,如果不清,则图像不断叠加 clear figure
plt.cla() # 清除坐标轴 clear axis
plt.xlim(0, 12) # x_min, x_max
plt.ylim(0, 1.5) # y_min, y_max
plt.title('Val Distribu')
plt.xlabel('Time')
plt.ylabel('Val')
plt.grid(linestyle='-.')
# create gif
y = ndata[i]
plt.plot(x[:], y[:], 'b', lw=1)
plt.savefig('temp.png')
image_list.append(imageio.imread('temp.png'))
# plt.show()
plt.pause(0.1)
plt.close()
# save gif
imageio.mimsave(output_path, image_list, 'GIF', duration=0.35)
if __name__ == "__main__":
row = 10
col = 20
data = np.random.rand(row, col) # 随机生成row行,col列,0-1的数据
output_path = './demo.gif'
generate_gif_1(data, output_path)
print('done!')
- 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
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
效果如下:
参考资料
- 【Python可视化】matplotlib画动态曲线,link
- 用python做GIF动画,让你的图表动起来, link