# How can I perform integral on a select area from ”active” line plot – python [closed]

I think the correct tool to accomplish this is the SpanSelector. Below is some code that adjusts the matplotlib example to do what you want. It will put the value of the integral into the plot title, but you could also print it out or save it to a variable if you wanted. Finally I also added a gray region to show what the selected region is.

``````import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import SpanSelector

# Fixing random state for reproducibility
np.random.seed(19680801)

fig, ax = plt.subplots()

x = np.arange(0.0, 5.0, 0.01)
y = np.sin(2*np.pi*x) + x

ax.plot(x, y, '-')

# create the gray span to show what we've selected
selected = ax.axvspan(0, 0, color='black', alpha=.25)
selected.set_visible(False)

def onselect(xmin, xmax):
# calculate the integral
indmin, indmax = np.searchsorted(x, (xmin, xmax))
indmax = min(len(x) - 1, indmax)
integral = np.trapz(y[indmin:indmax], x[indmin:indmax])
ax.set_title(f"The integral of the selected area is {integral}")

# update the visualization of the selected area
selected.set_visible(True)
xy = selected.get_xy()
xy[[0,1],0] = xmin
xy[[2,3],0] = xmax
selected.set_xy(xy)

fig.canvas.draw()

span = SpanSelector(ax, onselect, 'horizontal', useblit=True,
rectprops=dict(alpha=0.5, facecolor='red'))
# Set useblit=True on most backends for enhanced performance.

plt.show()
``````