Matplotlib: draw a selection area in the shape of a rectangle with the mouse

前端 未结 2 1184
星月不相逢
星月不相逢 2020-12-08 17:36

I want to be able to draw a selection area on a matplotlib plot with a mouse event. I didn\'t find information on how to do it with python.

In the end, I want to be

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-08 18:06

    Here's a small example that shows how to use the mouse to draw a rectangle on a matplotlib plot.

    import matplotlib.pyplot as plt
    from matplotlib.patches import Rectangle
    
    class Annotate(object):
        def __init__(self):
            self.ax = plt.gca()
            self.rect = Rectangle((0,0), 1, 1)
            self.x0 = None
            self.y0 = None
            self.x1 = None
            self.y1 = None
            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
            self.y0 = event.ydata
    
        def on_release(self, event):
            print 'release'
            self.x1 = event.xdata
            self.y1 = event.ydata
            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()
    
    a = Annotate()
    plt.show()
    

提交回复
热议问题