持久矩形选择器

时间:2015-12-29 19:11:18

标签: python matplotlib

我正在尝试开发一个处理天文数据的管道。在某些时候,我需要在图像上绘制一个矩形来选择一个区域。我正在使用matplotlib.widgets.RectangleSelector。因为它非常容易使用,所以使用它非常方便。唯一的问题"我有的是,在我释放鼠标按钮后,我在轴上绘制的矩形消失了。有没有办法让它持久?我的意思是,即使我释放按钮,有什么方法可以让它留在那里吗?

我使用Matplotlib的例子作为参考。 http://matplotlib.org/examples/widgets/rectangle_selector.html

1 个答案:

答案 0 :(得分:3)

更新:不再需要此功能。使用当前版本的matplotlib,2.0.2,释放鼠标时example in the docs仍然存在。

矩形消失,因为RectangleSelector的release方法调用

    # make the box/line invisible again
    self.to_draw.set_visible(False)
    self.canvas.draw()

要修改此行为,您可以继承RectangleSelector并为其提供自己的release方法:

class MyRectangleSelector(widgets.RectangleSelector):
    def release(self, event):
        super(MyRectangleSelector, self).release(event)
        self.to_draw.set_visible(True)
        self.canvas.draw()

因此建立在the docs

的示例上
from __future__ import print_function
import matplotlib.widgets as widgets
import numpy as np
import matplotlib.pyplot as plt

class MyRectangleSelector(widgets.RectangleSelector):
    def release(self, event):
        super(MyRectangleSelector, self).release(event)
        self.to_draw.set_visible(True)
        self.canvas.draw()

def line_select_callback(eclick, erelease):
    'eclick and erelease are the press and release events'
    x1, y1 = eclick.xdata, eclick.ydata
    x2, y2 = erelease.xdata, erelease.ydata
    print("(%3.2f, %3.2f) --> (%3.2f, %3.2f)" % (x1, y1, x2, y2))
    print(" The button you used were: %s %s" % (eclick.button, erelease.button))


def toggle_selector(event):
    print(' Key pressed.')
    if event.key in ['Q', 'q'] and toggle_selector.RS.active:
        print(' RectangleSelector deactivated.')
        toggle_selector.RS.set_active(False)
    if event.key in ['A', 'a'] and not toggle_selector.RS.active:
        print(' RectangleSelector activated.')
        toggle_selector.RS.set_active(True)


fig, current_ax = plt.subplots()                    # make a new plotingrange
N = 100000                                       # If N is large one can see
x = np.linspace(0.0, 10.0, N)                    # improvement by use blitting!

plt.plot(x, +np.sin(.2*np.pi*x), lw=3.5, c='b', alpha=.7)  # plot something
plt.plot(x, +np.cos(.2*np.pi*x), lw=3.5, c='r', alpha=.5)
plt.plot(x, -np.sin(.2*np.pi*x), lw=3.5, c='g', alpha=.3)

print("\n      click  -->  release")

# drawtype is 'box' or 'line' or 'none'
toggle_selector.RS = MyRectangleSelector(current_ax, line_select_callback,
                                       drawtype='box', useblit=True,
                                       button=[1, 3],  # don't use middle button
                                       minspanx=5, minspany=5,
                                       spancoords='pixels')
plt.connect('key_press_event', toggle_selector)
plt.show()