我对 Python 很陌生,正在尝试使用 matplotlib 为文本设置动画.使用了几个在线示例得出以下代码:
I'm quite new to Python and am trying to animate text using matplotlib. used several online examples to arrive at the following code:
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig, ax = plt.subplots()
plt.xlabel('Distance')
plt.ylabel('Height')
plt.title('Object Trajectory
')
plt.legend(loc="upper right", markerscale=4, fontsize=10)
plt.grid()
text=ax.text(3,1,'Moving Text', ha="left", va="bottom",clip_on=True,rotation=90,fontsize=15)
text2=ax.text(0,1,'Moving Text', ha="left", va="bottom",clip_on=True,fontsize=15)
def init():
ax.set_xlim(0,10)
ax.set_ylim(0,10)
return text,text2
def update(frame):
#Moving a text
text=ax.text(3,1+(int(frame))/30,'Moving Text', ha="left", va="bottom",clip_on=True,rotation=90,fontsize=15)
text2=ax.text(0+(int(frame))/30,1,'Moving Text', ha="left", va="bottom",clip_on=True,fontsize=15)
return text,text2
anim = animation.FuncAnimation(fig, update, init_func=init, frames=120, interval=10, blit=True)
anim.save('try_animation.mp4',dpi=160,fps=30, writer="ffmpeg")
plt.show()
所以当我在控制台中运行它时,我可以看到文本很好地移动.但是当我将它保存到 MP4 文件时,文本似乎并没有出现 blit.请帮忙.
So when I run it in console, I can see the texts moving nicely. But when I save it to a MP4 file the text doesn't seem to blit. Please Help.
谢谢
这是已保存视频文件的截图
您观察到的是预期的行为.Blitting 是一种用于仅刷新图形输出的一部分的技术.在 matplotlib 的情况下,不是绘制完整的图形,而是只刷新它的一部分,即轴内的区域,并且只绘制动画函数返回的那些艺术家.这允许在屏幕上具有更快的动画速度.
What you observe is the expected behaviour. Blitting is a technique used to refresh only part of a graphics output. In the matplotlib case, instead of drawing the complete figure, only part of it, namely the region inside the axes, is refreshed and only those artists returned by the animating function are drawn. This allows to have a faster animation speed on screen.
但是,在保存动画时,需要完整绘制每一帧.
因此,为了让文本移动,应该更新单个文本的位置,而不是一遍又一遍地创建新文本.这可以通过
So in order to have a text moving, one should rather update a single text's position, instead of creating new texts over and over again. This can be done with
text.set_position((x,y))
该示例因此看起来像
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig, ax = plt.subplots()
plt.xlabel('Distance')
plt.ylabel('Height')
plt.title('Object Trajectory
')
plt.grid()
text=ax.text(3,1,'Moving Text', ha="left", va="bottom",clip_on=True,rotation=90,fontsize=15)
text2=ax.text(0,1,'Moving Text', ha="left", va="bottom",clip_on=True,fontsize=15)
def init():
ax.set_xlim(0,10)
ax.set_ylim(0,10)
return text,text2
def update(frame):
#Moving a text
text.set_position((3, 1+(int(frame))/30))
text2.set_position((0+(int(frame))/30,1))
return text,text2
anim = animation.FuncAnimation(fig, update, init_func=init, frames=120, interval=10, blit=True)
anim.save('try_animation.mp4',dpi=160,fps=30, writer="ffmpeg")
plt.show()
这篇关于matplotlib 动画保存不遵守 blit=True 但它似乎在 plt.show() 中工作得很好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!