Python:从Seaborn kdeplot获取FWHM

问题描述

我在某些数据上使用了Seaborn的kdeplot。

typed_config

是否可以从创建的曲线返回fwhm? 如果没有,还有另一种计算方法吗?

解决方法

我不相信有一种无需编写代码即可计算出随机数据图中数据的方法。

考虑一些示例数据:

import numpy as np

arr_x = np.linspace(norm.ppf(0.00001),norm.ppf(0.99999),10000)
arr_y = norm.pdf(arr_x)

找到最小和最大点并计算差。

difference = max(arr_y) - min(arr_y)

找到最大一半(在本例中为一半)

HM = difference / 2

找到最接近HM的数据点:

nearest = (np.abs(arr_y - HM)).argmin()

计算最接近值与最小值之间的距离以获取HWHM,然后乘以2以得出FWHM。

,

您可以从斧头提取生成的kde曲线。然后获得最大的y值,并搜索最接近一半最大值的x位置:

import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt

ax = sns.kdeplot(np.random.rand(100))
kde_curve = ax.lines[0]
x = kde_curve.get_xdata()
y = kde_curve.get_ydata()
halfmax = y.max() / 2
maxpos = y.argmax()
leftpos = (np.abs(y[:maxpos] - halfmax)).argmin()
rightpos = (np.abs(y[maxpos:] - halfmax)).argmin() + maxpos
fullwidthathalfmax = x[rightpos] - x[leftpos]
ax.hlines(halfmax,x[leftpos],x[rightpos],color='crimson',ls=':')
ax.text(x[maxpos],halfmax,f'{fullwidthathalfmax:.3f}\n',ha='center',va='center')
ax.set_ylim(ymin=0)
plt.show()

example plot

请注意,如果不需要绘图版本,也可以根据scipy.stats.gaussian_kde计算kde曲线。在这种情况下,代码可能类似于:

import numpy as np
from scipy.stats import gaussian_kde

data = np.random.rand(100)
kde = gaussian_kde(data)
x = np.linspace(data.min(),data.max(),1000)
y = kde(x)
halfmax = y.max() / 2
maxpos = y.argmax()
leftpos = (np.abs(y[:maxpos] - halfmax)).argmin()
rightpos = (np.abs(y[maxpos:] - halfmax)).argmin() + maxpos
fullwidthathalfmax = x[rightpos] - x[leftpos]
print(fullwidthathalfmax)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...