我希望能够在动画运行或停止状态时更改动画绘图的 xlim 和 ylim。在动画运行时更改它们(使用 ax.set_xlim/set_ylim 调用)效果很好,但如果我使用 event_source.stop() 暂停动画,则沿坐标轴绘制的数字将保持不变。
这是显示此问题的测试程序。尝试在动画运行时按“-”和“+”键 --- 您将看到蓝色对象已缩放并且坐标范围已更新。但是,如果您首先按空格键暂停动画,然后按“-”或“+”,则只有蓝色对象会缩放,但坐标范围保持原样(并且动画会作为调用的副作用而恢复) ani._end_redraw(无))。
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from numpy import sin, cos, pi
def keypress(event):
global anim_running
if event.key == ' ':
ani.event_source.stop() if anim_running else ani.event_source.start()
anim_running = not anim_running
elif event.key == '+':
ax.set_xlim([-4,4])
ax.set_ylim([-4,4])
ani._end_redraw(None)
elif event.key == '-':
ax.set_xlim([-1,1])
ax.set_ylim([-1,1])
ani._handle_resize()
ani._end_redraw(None)
phi = pi/2
def animate(i):
global phi
line.set_data([[0.0, sin(phi)], [0.0, cos(phi)]])
phi += 0.01
return line,
fig,ax = plt.subplots(1, 1)
ax.set_xlim([-2,2])
ax.set_ylim([-2,2])
line, = ax.plot([], [], 'o-', lw=2, color='b')
fig.canvas.mpl_connect('key_press_event', keypress)
ani = animation.FuncAnimation(fig, animate, blit=True, interval=0, frames=2000)
anim_running = True
plt.show()
最佳答案
应重新绘制完整的 Canvas ,以确保可以观察到限制的更改。我想一个好的策略是 1. 更改限制,2. 绘制 Canvas ,3. 停止动画,获取新背景(通过 _handle_resize
),4. 重新启动动画(通过 _end_redraw
)
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from numpy import sin, cos, pi
def keypress(event):
global anim_running
if event.key == ' ':
ani.event_source.stop() if anim_running else ani.event_source.start()
anim_running = not anim_running
elif event.key == '+':
ax.set_xlim([-4,4])
ax.set_ylim([-4,4])
fig.canvas.draw()
ani._handle_resize()
ani._end_redraw(None)
elif event.key == '-':
ax.set_xlim([-1,1])
ax.set_ylim([-1,1])
fig.canvas.draw()
ani._handle_resize()
ani._end_redraw(None)
phi = pi/2
def animate(i):
global phi
line.set_data([[0.0, sin(phi)], [0.0, cos(phi)]])
phi += 0.01
return line,
fig,ax = plt.subplots(1, 1)
ax.set_xlim([-2,2])
ax.set_ylim([-2,2])
line, = ax.plot([], [], 'o-', lw=2, color='b')
fig.canvas.mpl_connect('key_press_event', keypress)
ani = animation.FuncAnimation(fig, animate, blit=True, interval=2, frames=2000)
anim_running = True
plt.show()
关于python - 如何在matplotlib中调整暂停动画的坐标范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47439104/