import xlrd
import matplotlib.pyplot as plt
import matplotlib.animation as animation
book = xlrd.open_workbook('test.xlsx')
sheet = book.sheet_by_name('Sheet1')
x = sheet.col_values(0)
y = sheet.col_values(1)
nrows = sheet.nrows
# fig表示figure窗体, ax表示axes绘图区
fig, ax = plt.subplots(1,1)
ims = []
for i in range(1, nrows):
im = ax.plot(x[1:i+1], y[1:i+1], color='r')
ims.append(im)
ani = animation.ArtistAnimation(fig, ims, interval=100, repeat_delay=1000)
ani.save('test.gif', writer='pillow')
plt.show()
test.xlsx部分内容如下:
运行结果:
思考:
欲使用ax.text(x[i],y[i],‘x:%d y:%d’ % (x[i],y[i]))在图像中添加文本,实时显示x,y坐标值,但测试不成功。后来想到一个笨拙的办法,那就是先得到N张ax.plot(x[1:i+1], y[1:i+1], color=‘r’)图像,再得到N张ax.text(x[i],y[i],‘x:%d y:%d’ % (x[i],y[i]))图像,将它们两两合并,得到N张合并后的图像,最后将其制作成动画。
将gif动画拆分成N张图像:
import os
from PIL import Image
image = Image.open('test.gif')
try:
i = 0
while True:
image.seek(i)
image.save('images\\'+str(i)+'.png')
i += 1
except:
pass
将N张图像合成gif动画:
import os
import imageio
images = []
for filename in os.listdir('images'):
images.append(imageio.imread('images\\' + filename))
imageio.mimsave('test.gif',images,'GIF',duration=0.1)