按下'1'按钮后缩放停止工作,但仅在子图中



我正在开发一个简单的GUI,使用Matplotlib自己的事件处理来分析一些数据。这通常效果很好,但在过去的几个小时里,我一直在一些奇怪的错误上挠头。

下面的代码是我真实应用程序的严重削减版本。它的工作方式是,您可以通过单击鼠标左键和右键单击图像来添加和删除点。可以通过按"0"和"1"键打开和关闭此"编辑模式"。

当图像是唯一的子图时,这工作正常。错误在于,如果图像是几个子图中的一个,则一旦您打开编辑模式(通过按"1"按钮,将on_click函数安装为button_press_event的处理程序(,Matplotlib 的缩放按钮就会停止工作。在此之后,按"o"或缩放按钮会更改光标,但缩放区域的矩形不再出现。我猜处理程序以某种方式弄乱了 Matplotlib 的内部结构。

有谁明白为什么在单个子图的情况下缩放继续工作,但在多个子图的情况下安装on_click处理程序时停止工作?在工作版本和错误版本之间切换注释/取消注释生成图形和子图的指示行。我正在使用python 2.7.14和matplotlib 2.2.2,两者都来自anaconda。

import numpy as np
import matplotlib.pyplot as plt
class Points(object):
def __init__(self, ax):
self.ax = ax
# make dummy plot, points will be added later
self.dots, = ax.plot([], [], '.r')
self.x = []
self.y = []
def onclick(self, event):
print 'point.onclick'
# only handle clicks in the relevant axis
if event.inaxes is not self.ax:
print 'outside axis'
return
# add point with left button
if event.button == 1:
self.x.append(event.xdata)
self.y.append(event.ydata)
# delete point with right button
if event.button == 3 and len(self.x) > 0:
imn = np.argmin((event.xdata - self.x)**2 + (event.ydata - self.y)**2)
del self.x[imn]
del self.y[imn]
self.dots.set_data(self.x, self.y)
plt.draw()
#### THIS WORKS ####
fig, ax3 = plt.subplots()
####################
#### THIS DOES NOT WORK ####
# fig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(2, 2)
############################
ax3.imshow(np.random.randn(10, 10))
ax3.set_title('Press 0/1 to disable/enable editing points')
points = Points(ax3)
# initial state
cid_click = None
state = 0
def on_key(event):
global cid_click, state
print 'you pressed %r' % event.key
if event.key in '01':
if cid_click is not None:
print 'disconnect cid_click', cid_click
fig.canvas.mpl_disconnect(cid_click)
cid_click = None
state = int(event.key)
if state:
print 'connect'
cid_click = fig.canvas.mpl_connect('button_press_event', points.onclick)
# plt.draw()
print 'state = %i, cid = %s' % (state, cid_click)
cid_key = fig.canvas.mpl_connect('key_press_event', on_key)
plt.show()

这是我迄今为止遇到的最奇怪的错误之一。该问题与按1键有关。由于某种未知的原因,这似乎杀死了其他事件的回调。我创建了一个关于它的错误报告。

目前,解决方案是不使用1键,而是使用A/D键(用于激活/停用(。

# initial state
cid_click = None
state = "d"
def on_key(event):
global cid_click, state
print 'you pressed %r' % event.key
if event.key in 'ad':
if cid_click is not None:
print 'disconnect cid_click', cid_click
fig.canvas.mpl_disconnect(cid_click)
cid_click = None
state = event.key
if state == "a":
print 'connect'
cid_click = fig.canvas.mpl_connect('button_press_event', points.onclick)
print 'state = %s, cid = %s' % (state, cid_click)

最新更新