您好我正在制作一个小程序来从绘图中选择数据。我想使用内置的matplotlib.widgets,但我误解了连接/断开图形画布的基础知识。
下面是我想到的代码示例。如果我在事件管理器类之外声明游标/ span小部件,则小部件将正确启动。但是,Event_Manager类中的情况并非如此。
但是我应该如何修改代码以使用键事件启动这些小部件?另外,我如何使用关键事件来解除/重新解决它们?
import matplotlib.widgets as widgets
import numpy as np
import matplotlib.pyplot as plt
def Span_Manager(Wlow,Whig):
print Wlow,Whig
return
class Event_Manager:
def __init__(self, fig, ax):
self.fig = fig
self.ax = ax
self.redraw()
def redraw(self):
self.fig.canvas.draw()
def connect(self):
self.fig.canvas.mpl_connect('key_press_event', self.onKeyPress)
def onKeyPress(self, ev):
if ev.key == 'q':
print 'activate span selector'
Span = widgets.SpanSelector(ax, Span_Manager, 'horizontal', useblit=False, rectprops=dict(alpha=1, facecolor='Blue'))
elif ev.key == 'w':
print 'activate cursor'
cursor = widgets.Cursor(ax, useblit=True, color='red', linewidth=2)
self.redraw()
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111)
x, y = 4*(np.random.rand(2, 100)-.5)
ax.plot(x, y, 'o')
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)
mat_wid = Event_Manager(fig, ax)
mat_wid.connect()
# Span = widgets.SpanSelector(ax, Span_Manager, 'horizontal', useblit=False, rectprops=dict(alpha=1, facecolor='Blue'))
# cursor = widgets.Cursor(ax, useblit=True, color='red', linewidth=2)
plt.show()