如何解决在 Python 中仅重绘特定的轴对象
我正在尝试使用 matplotlib 专门用 Python 编写一个小型视频游戏。这个想法是在一个在更大地图上移动的小轴对象上有一个角色。我设法更新了轴的位置,但该方法似乎重绘了完整图形而不是小轴对象(通过在源代码中调用 plt.draw() ),因此角色背后的重图也使过程极其缓慢。
有没有办法在 matplotlib 中重绘特定的轴对象?
我在终端的 IPython shell 中工作。
这是一个模拟我的问题的测试代码,其中我获得的东西比理想情况慢 10 倍:
import matplotlib.pylab as plt
import time
import numpy as np
dtframe = 0.02 #time between plot updating in seconds
frames = 30
plt.subplots(5,5) #to simulate an heavy background matplotlib figure
ax = plt.axes([0.1,0.5,0.03,0.03])
plt.show(block=False)
begin = time.time()
for j in np.linspace(0.1,0.9,frames):
plt.pause(dtframe)
ax.set_position([j,0.03])
#ax.set_position([j,0.03],redraw_only_axes=True) ???
print('Current time [s] :',time.time() - begin)
print('Expected time [s] :',dtframe*frames)
#Current time [s] : 5.70146918296814
#Expected time [s] : 0.6
解决方法
您正在寻找的技术称为块传输。
这里有关于在 matplotlib 中执行此操作的教程:https://matplotlib.org/stable/tutorials/advanced/blitting.html
,基于@ianhi 提供的教程,这里是使用 blitting 的解决方案:
import matplotlib.pylab as plt
import time
import numpy as np
dtframe = 0.02 #time between plot updating in seconds
frames = 30
fig,axes = plt.subplots(5,5) #to simulate an heavy background matplotlib figure
ax = plt.axes([0.1,0.5,0.03,0.03],animated=True)
plt.show(block=False)
plt.pause(0.1)
bg = fig.canvas.copy_from_bbox(fig.bbox)
fig.canvas.blit(fig.bbox)
begin = time.time()
for j in np.linspace(0.1,0.9,frames):
fig.canvas.restore_region(bg)
ax.set_position([j,0.03])
plt.pause(dtframe)
fig.draw_artist(ax)
fig.canvas.blit(fig.bbox)
fig.canvas.flush_events()
print('Current time [s] :',time.time() - begin)
print('Expected time [s] :',dtframe*frames)
#Current time [s] : 1.2531671524047852
#Expected time [s] : 0.6
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。