1

I have a distribution and I wish to integrate over a custom range selected by the user's mouse click on the distribution's plot.

import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
from scipy.integrate import trapz

# Probability Density Function
pdf = stats.norm.pdf

#adjust the location and scale of the distribution
loc1, scale1, size1 = (20, 1.5, 500)
loc2, scale2, size2 = (28, 2.5, 500)

# Probability Density Function
pdf = stats.norm.pdf
x2 = np.concatenate([np.random.normal(loc=loc1, scale=scale1, size=size1),np.random.normal(loc=loc2, scale=scale2, size=size2)])
x_eval = np.linspace(x2.min() - 1, x2.max() + 1, 1000)
bimodal_pdf = pdf(x_eval, loc=loc1, scale=scale1) * float(size1) / x2.size + pdf(x_eval, loc=loc2, scale=scale2) * float(size2) / x2.size

plt.figure()
plt.plot(x_eval,bimodal_pdf)
plt.show()

At this point I would like to be able to select the lower and upper bounds of x over which the integral of y will be calculated.

ie.

a = User mouse click x position 1
b = User mouse click x position 2

area = trapz(y[a,b], x[a:b])


print 'the area under curve between x1 and x2 = ' + str(area)
1
  • 1
    matplotlib has an event handling system that can give you info about mouse clicks, etc. have you tried it? matplotlib.org/users/event_handling.html Commented Feb 28, 2014 at 0:42

1 Answer 1

3

If you want the simplest possible option, use point1, point2 = plt.ginput(2).

point1 and point2 will be tuples of x,y, so you'd want a, b = point1[0], point2[0] in your example.

As a quick example:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.set(title='Click Twice', xlabel='X', ylabel='Y')

point1, point2 = fig.ginput(2) # Or equivalently, "plt.ginput"

ax.autoscale(False)
ax.axvspan(point1[0], point2[0], color='red', alpha=0.5)
fig.canvas.draw()

plt.show()
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this is very nearly it! Is there a way of returning the indices of the x array, rather than the value itself?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.