python - 用户鼠标在绘图上输入积分限制 - python

标签 python matplotlib mouseevent integration

我有一个分布,我希望在用户通过鼠标单击分布图而选择的自定义范围内进行积分。

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()

此时,我希望能够选择 x 的下限和上限,并在其上计算 y 的积分。

即。

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)

最佳答案

如果您想要最简单的选项,请使用point1, point2 = plt.ginput(2)

point1point2 将是 x,y 的元组,因此您需要 a, b = point1[0], point2[0] 在您的示例中。

举个简单的例子:

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()

关于python - 用户鼠标在绘图上输入积分限制 - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22083381/

相关文章:

python - Pyqt 鼠标 MouseButtonDblClick 事件

.net - 如何检测是否同时按下了左右按钮?

python - 如何在 Windows 10 PC 上创建 Docker 容器以在 Raspberry Pi 4 上运行

python - Pyplot 堆积直方图 - 列中出现的次数

python - Django - 每 x 秒运行一个函数

python - 属性错误: Unknown property column

python - Seaborn:指定确切的颜色

python - 如何用数据框中的所有行名称标记轴

python - 如何保持列表的一致性?

javascript - mousedown 内的 mousemove 停止鼠标弹起