如何将 `mpl_connect` 限制为 `axes` 而不是整个 `figure`?

How to limit `mpl_connect` to an `axes` instead of a whole `figure`?

我正在编写一个程序,用户可以在其中以交互方式修改情节。我正在使用 3 个 mpl_connect 函数 (key_press_event button_press_event button_release_event) 加上 4 个文本框 (mwidgets.TextBox).

每次我在文本框中键入文本时,过程都很慢,我认为这是因为当我在文本框上单击和书写时,不必要地 触发了 3 "mpl connections" (key_press_event button_press_event button_release_event).

3 个文本框在 "axes object" 之外,所以我想知道是否有办法将 "mpl conections" 限制在感兴趣的轴内。也就是说,不是编写以下代码:

cid1 = figure.canvas.mpl_connect('key_press_event', onPressKey)
cid2 = figure.canvas.mpl_connect('button_press_event', onPressButton)
cid3 = figure.canvas.mpl_connect('button_release_event', onReleaseButton)

编写如下代码(注意用 canvas 代替 axes):

cid1 = figure.axes.mpl_connect('key_press_event', onPressKey)
cid2 = figure.axes.mpl_connect('button_press_event', onPressButton)
cid3 = figure.axes.mpl_connect('button_release_event', onReleaseButton)

有什么解决方法吗?

欢迎任何评论!

看看这个简单的例子,看看 print 语句 return:

import numpy as np
import matplotlib as mpl

import matplotlib.pyplot as plt
from matplotlib.widgets import TextBox

fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.2)
t = np.arange(-2.0, 2.0, 0.001)
s = t ** 2
initial_text = "t ** 2"
l, = plt.plot(t, s, lw=2)

def submit(text):
    ydata = eval(text)
    l.set_ydata(ydata)
    ax.set_ylim(np.min(ydata), np.max(ydata))
    plt.draw()

def onPressKey(event):
    print('you pressed key {0} in ax {1}'.format( event.key, event.inaxes ))
    if event.inaxes in [ax]:
        print("in ax")
    elif event.inaxes in [fig.axes[1]]:
        print("in cid1")
    else:
        print("outside")


axbox = plt.axes([0.1, 0.05, 0.8, 0.075])
text_box = TextBox(axbox, 'Evaluate', initial=initial_text)
text_box.on_submit(submit)

fig.canvas.mpl_connect('key_press_event', onPressKey)

plt.show()

如果您将鼠标悬停在 "plot region"(即 axfig.axes[0])上,您按下的每个键都会触发默认键绑定 (i.s。s 触发保存对话框)。

onPressKey(event) 处理程序已经可以用来决定如何处理此输入,因为它知道 event.inaxes,即您的鼠标在 key_press_event 期间的位置。 但是请注意,一旦您在 TextBox 小部件内单击,它将捕获您的输入(即 s 被写入其中,不会触发保存对话框)。 如果您现在将鼠标 移到 texbox 之外,onPressKey(event) 处理程序仍会让您知道您的 mouseax 在文本输入期间(或者可能 "outside"),但这 不会改变 TextBox 小部件仍然捕获您的输入的事实,直到您例如按 输入 .

简短回答:您不想将 key_press_event 连接到特定轴,而是想让 onPressKey(event) 处理程序,很好处理它。每次击键都应注册为 一个 key_press_event,因此这可能不是您的问题的罪魁祸首(好吧,除非您的实际代码是例如设置为在例如上进行一些昂贵的计算)按下 e 键,您 忘记了 先在 TextBox 中单击。)