我正在创建一个matplotlib动画,根据用户输入显示在flask应用程序上。matplotlib脚本类似于:
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
# Horizontal bar plot with gaps
fig, ax = plt.subplots()
ax.get_yaxis().set_visible(False)
ax.spines[['top', 'bottom','left','right']].set_visible(False)
y2=[20,20,20,20,20,20,20]
y3=np.array(y2) #convert to array wont work with list
x2 =[20,15,14,13, 12,11,10]
x3=np.array(x2)
year =["2014","2015","2016","2017","2018","2019","2020"]
yr2 =np.array(year)
def animate(i):
ax.clear()
ax.set_ylim(16, 24)
ax.barh(20, 60, 4 )
ax.plot(60, 18, marker=6, markersize=18, clip_on=False,)
ax.annotate(r"$\bf" + str(2013) +"$" + f" ({60})", (60 , 18),xytext=(0, -25), size= 8, textcoords='offset points', ha='center', va='bottom')
ax.barh(y3[i], x3[i], 4,color='c')
ax.plot(x3[i], y3[i]+2, color = 'c', marker=7, markersize=18, clip_on=False,)
ax.annotate(r"$\bf" + str(yr2[i]) +"$" + f" ({x3[i]})", (x3[i] , y3[i]+2),xytext=(0, 15), size= 8, color = 'c', textcoords='offset points', ha='center', va='bottom')
ani = animation.FuncAnimation(fig, animate, repeat=False,
frames=len(x3), interval=100000)
# To save the animation using Pillow as a gif
writer = animation.PillowWriter(fps=1,
metadata=dict(artist='Me'),
bitrate=1800)
ani.save('scatter.gif', writer=writer)
字符串
是否可以将gif保存到内存文件中,而不是保存为gif?
1条答案
按热度按时间k97glaaz1#
tempfile
,使用io.BytesIO
将其加载到内存中,然后删除该文件。buf = io.BytesIO()
和ani.save(buf, writer=writer)
无法将动画直接保存到缓冲区,因为ani.save
不接受BytesIO
作为路径。python 3.9.18
,flask 2.2.2
,matplotlib 3.7.2
,numpy 1.21.5
中测试。字符串
的数据
根据OP基于Given a BytesIO buffer, generate img tag in html的评论进行更新。
型