我一直在尝试使用类似于ChrisB在另一个stackoverflow问题(Matplotlib: draw a selection area in the shape of a rectangle with the mouse)中发布的解决方案的代码,以允许用户通过单击/拖动鼠标来选择绘图区域的区域。我编写了一个测试代码,可以很好地工作,但是当我将其合并到主代码中时,该功能就会停止。 on_click和on_release方法似乎从未被调用。下面是我的regionSelecter类代码。
class regionSelecter(object):
def __init__(self):
self.ax = plt.gca()
self.rect = Rectangle((0,0), 0, 0, fill=False)
self.x0 = None
self.y0 = self.ax.get_ylim()[0]
self.x1 = None
self.y1 = self.ax.get_ylim()[1]
self.ax.add_patch(self.rect)
self.ax.figure.canvas.mpl_connect('button_press_event', self.on_press)
self.ax.figure.canvas.mpl_connect('button_release_event', self.on_release)
def on_press(self, event):
print('press')
self.x0 = event.xdata
def on_release(self, event):
print('release')
self.x1 = event.xdata
self.rect.set_width(self.x1 - self.x0)
self.rect.set_height(self.y1 - self.y0)
self.rect.set_xy((self.x0, self.y0))
self.ax.figure.canvas.draw()
print(self.x0)
print(self.y0)
print(self.x1)
print(self.y1)
这是我的测试代码
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Rectangle
xdata = np.linspace(0,9*np.pi, num=100)
ydata = np.sin(xdata)
ax = plt.subplots()[1]
bar = ax.bar(xdata, ydata)
rs = regionSelecter()
plt.show()
最后,我的主要代码
"""
creates spectrum plot
"""
def specPlot(rng, index):
global df
spec = df.iloc[index, (df.shape[1] - rng):] # Get spectrum
ax = plt.subplots()[1]
ax.bar(range(rng), spec, width=4) # Plot spectrum
s=regionSelecter()
plt.show()
df是熊猫数据框,spec是该数据框的切片,其中包含一系列数字,rng是该系列的长度。为什么我的regionSelecter类在主代码和测试代码中的行为会有所不同?