matplotlib 事件的退出递归 [英] Exit recursion for matplotlib events

查看:83
本文介绍了matplotlib 事件的退出递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 button_press_event 的 matplotlib 图.在侦听器中,我使用 plt.pause 为每次点击制作一个简短的动画.这工作正常并且符合预期.但是,如果我在动画结束之前再次单击,我会输入一个递归并在最后播放剩余的动画.如果您点击足够快,您甚至可以到达 RecursionError.

I have a little matplotlib figure with a button_press_event. Inside the listener I use plt.pause to make a short animation for every click. This works fine and as expected. However if I click again before the animation is over, I enter a recursion and the remaining animations are played at the end. If you click fast enough you can even reach the RecursionError.

我需要更改什么,以便新的点击丢弃 on_click 方法中的所有剩余步骤?

What do I need to change, so a new click discards all remaining steps in the on_click method?

import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.subplots()

ax.set_xlim(0, 10)
ax.set_ylim(0, 10)

xy = np.random.random(2)*10
h1 = ax.plot(xy[0], xy[1], marker='x', color='k')[0]
h2 = ax.plot(xy[0], xy[1], marker='o', color='r')[0]

def on_click(event):
    h1.set_xdata(event.xdata)
    h1.set_ydata(event.ydata)
    for i in range(10):
        h2.set_xdata(event.xdata+np.random.random()-0.5)
        h2.set_ydata(event.ydata+np.random.random()-0.5)
        plt.pause(0.1)

cid_click = fig.canvas.mpl_connect('button_press_event', on_click)

推荐答案

您可以使用 FuncAnimation.然后确保在新动画开始之前停止并删除以前的动画.

You could use a FuncAnimation. Then make sure to stop and delete previous animations before a new animation starts.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()

ax.set_xlim(0, 10)
ax.set_ylim(0, 10)

xy = np.random.random(2)*10
h1 = ax.plot(xy[0], xy[1], marker='x', color='k')[0]
h2 = ax.plot(xy[0], xy[1], marker='o', color='r')[0]

anis = []
def on_click(event):
    h1.set_xdata(event.xdata)
    h1.set_ydata(event.ydata)
    def animate(i):
        h2.set_xdata(event.xdata+np.random.random()-0.5)
        h2.set_ydata(event.ydata+np.random.random()-0.5)
    for ani in anis:
        ani.event_source.stop()
        anis.remove(ani)
        del ani
    anis.append(FuncAnimation(fig, animate, frames=10, repeat=False))
    fig.canvas.draw_idle()

cid_click = fig.canvas.mpl_connect('button_press_event', on_click)

plt.show()

这篇关于matplotlib 事件的退出递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆