Matplotlib连接按下/释放事件在测试代码中有效,但在真实代码中无效

2024-09-27 22:33:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试使用类似于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类在主代码和测试代码中的行为会有所不同


Tags: 代码rectselfeventreleaseondefplt

热门问题