user6528780
user6528780

Reputation:

Rectangle to select area in plot and find maximum value

I am looking for advice on where to begin to code my latest project.

I would like to be able to draw slightly transparent rectangles on a matplotlib plot and return the values within this square. The end goal of this project is to return the largest value in this area and use it for further analysis later.

This is something I have not personally seen done before and have no clue where to start with this project. I am hoping to be pointed in the right direction with this code.

Thank you for any advice you can give.

example of final look.

Upvotes: 3

Views: 4484

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339300

To draw a rectangle interactively, you may use a RectangleSelector. There is an example at the matplotlib page.

You can then find out which points lie in the range of the rectangle and find the maximum using respective numpy functions.

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)*np.cos(xdata*2.4)

fig, ax = plt.subplots()
line, = ax.plot(xdata, ydata)
point, = ax.plot([],[], marker="o", color="crimson")
text = ax.text(0,0,"")

def line_select_callback(eclick, erelease):
    x1, y1 = eclick.xdata, eclick.ydata
    x2, y2 = erelease.xdata, erelease.ydata

    mask= (xdata > min(x1,x2)) & (xdata < max(x1,x2)) & \
          (ydata > min(y1,y2)) & (ydata < max(y1,y2))
    xmasked = xdata[mask]
    ymasked = ydata[mask]

    if len(xmasked) > 0:
        xmax = xmasked[np.argmax(ymasked)]
        ymax = ymasked.max()
        tx = "xmax: {:.3f}, ymax {:.3f}".format(xmax,ymax)
        point.set_data([xmax],[ymax])
        text.set_text(tx)
        text.set_position((xmax,ymax))
        fig.canvas.draw_idle()


rs = RectangleSelector(ax, line_select_callback,
                       drawtype='box', useblit=False, button=[1], 
                       minspanx=5, minspany=5, spancoords='pixels', 
                       interactive=True)

plt.show()

enter image description here

Upvotes: 8

Related Questions