绘制动图可以用一些现有的集成库,但是很麻烦,你需要调整和他们一样的参数和格式,定制化程度比较低,还得再去搞懂它们的东西。比如这些现有的:
https://github.com/JackMcKew/pandas_alive
使用Python PIL.Image 制作GIF图片:
import PIL.Image # 相关模块
img = Image.open(img_name) # 打开图片
img.save(save_name,save_all = True,\append_images = imgs,duration = t) #保存图片
append_images = imgs # imgs为存放对象们的列表
duration = t # GIF动图的间隔时间
代码如下:
import imageio
def create_gif(image_list, gif_name, duration = 1.0):
'''
:param image_list: 这个列表用于存放生成动图的图片
:param gif_name: 字符串,所生成gif文件名,带.gif后缀
:param duration: 图像间隔时间
:return:
'''
frames = []
for image_name in image_list:
frames.append(imageio.imread(image_name))
imageio.mimsave(gif_name, frames, 'GIF', duration=duration)
return
def main():
#这里放上自己所需要合成的图片
image_list = ['0.jpg', '1.jpg', '2.jpg']
gif_name = 'baby.gif'
duration = 0.2
create_gif(image_list, gif_name, duration)
if __name__ == '__main__':
main()
在matplotlib模块中使用最多的类是pyplot。pyplot位于matplotlib模块中脚本层为入门用户提供快速绘制折线、柱状、散点、饼图等图形方法,在matplotlib模块为用户提供快速绘制动态图,除了专门绘制的动态类animation类外,pyplot也提供绘制动态图相关方法。本期,我们将学习使用pyplot的绘制动态图相关方法
我们前面学习绘制的方法后,最后都会调用pyplot.show()方法,运行程序后才会显示图像。
在matplotlib模式中绘制图形通常有两种模式:
方法 | 作用 |
---|---|
pyplot.ion() | 打开交互模式 |
pyplot.ioff() | 关闭交互模式 |
pyplot.clf() | 清除当前的画布figure对象 |
pyplot.cla() | 清除当前Axes对象 |
pyplot.pause() | 暂停功能 |
import matplotlib.pyplot as plt
plt.ion()
x = np.linspace(0,np.pi*i+1,1000)
y = np.cos(x)
plt.xlim(-0.2,20.4)
plt.ylim(-1.2,1.2)
plt.plot(x,y,color="pink")
plt.cla()
plt.pause(0.1)
plt.ioff()
plt.show()
def scatter_plot():
# 打开交互模式
plt.ion()
for index in range(50):
# plt.cla()
plt.title("动态散点图")
plt.grid(True)
point_count = 5
x_index = np.random.random(point_count)
y_index = np.random.random(point_count)
color_list = np.random.random(point_count)
scale_list = np.random.random(point_count) * 100
plt.scatter(x_index, y_index, s=scale_list, c=color_list, marker="^")
plt.pause(0.2)
plt.ioff()
plt.show()