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

前端 未结 2 1183
星月不相逢
星月不相逢 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:13

    Matplotlib provides its own RectangleSelector. There is an example on the matplotlib page, which you may adapt to your needs.

    A simplified version would look something like this:

    import matplotlib.pyplot as plt
    import numpy as np
    from matplotlib.widgets  import RectangleSelector
    
    xdata = np.linspace(0,9*np.pi, num=301)
    ydata = np.sin(xdata)
    
    fig, ax = plt.subplots()
    line, = ax.plot(xdata, ydata)
    
    
    def line_select_callback(eclick, erelease):
        x1, y1 = eclick.xdata, eclick.ydata
        x2, y2 = erelease.xdata, erelease.ydata
    
        rect = plt.Rectangle( (min(x1,x2),min(y1,y2)), np.abs(x1-x2), np.abs(y1-y2) )
        ax.add_patch(rect)
    
    
    rs = RectangleSelector(ax, line_select_callback,
                           drawtype='box', useblit=False, button=[1], 
                           minspanx=5, minspany=5, spancoords='pixels', 
                           interactive=True)
    
    plt.show()
    

提交回复
热议问题