Joe*_*e B 6 python numpy matplotlib scipy kernel-density
我有一组要绘制高斯核密度估计值的值,但是我遇到两个问题:
这是我到目前为止生成的图:
y轴的顺序实际上是相关的,因为它代表每种细菌物种的系统发育。
我想为每种颜色添加一个高斯kde叠加层,但是到目前为止,我还无法利用seaborn或scipy做到这一点。
这是上面使用python和matplotlib分组的条形图的代码:
enterN = len(color1_plotting_values)
fig, ax = plt.subplots(figsize=(20,30))
ind = np.arange(N) # the x locations for the groups
width = .5 # the width of the bars
p1 = ax.barh(Species_Ordering.Species.values, color1_plotting_values, width, label='Color1', log=True)
p2 = ax.barh(Species_Ordering.Species.values, color2_plotting_values, width, label='Color2', log=True)
for b in p2:
b.xy = (b.xy[0], b.xy[1]+width)
Run Code Online (Sandbox Code Playgroud)
谢谢!
核密度估计协议需要底层数据。您可以提出一种使用经验 pdf(即直方图)的新方法,但它不会是 KDE 分布。
然而,并不是所有的希望都破灭了。您可以通过首先从直方图中获取样本,然后在这些样本上使用 KDE 来获得 KDE 分布的良好近似值。这是一个完整的工作示例:
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as sts
n = 100000
# generate some random multimodal histogram data
samples = np.concatenate([np.random.normal(np.random.randint(-8, 8), size=n)*np.random.uniform(.4, 2) for i in range(4)])
h,e = np.histogram(samples, bins=100, density=True)
x = np.linspace(e.min(), e.max())
# plot the histogram
plt.figure(figsize=(8,6))
plt.bar(e[:-1], h, width=np.diff(e), ec='k', align='edge', label='histogram')
# plot the real KDE
kde = sts.gaussian_kde(samples)
plt.plot(x, kde.pdf(x), c='C1', lw=8, label='KDE')
# resample the histogram and find the KDE.
resamples = np.random.choice((e[:-1] + e[1:])/2, size=n*5, p=h/h.sum())
rkde = sts.gaussian_kde(resamples)
# plot the KDE
plt.plot(x, rkde.pdf(x), '--', c='C3', lw=4, label='resampled KDE')
plt.title('n = %d' % n)
plt.legend()
plt.show()
Run Code Online (Sandbox Code Playgroud)
输出:
图中红色虚线和橙色线几乎完全重叠,表明真实的 KDE 和通过重采样直方图计算的 KDE 非常吻合。
如果你的直方图真的很嘈杂(就像你n = 10在上面的代码中设置的那样),除了绘图目的之外,在使用重新采样的 KDE 时你应该有点谨慎:
总体而言,真实 KDE 和重新采样的 KDE 之间的一致性仍然很好,但偏差很明显。
由于您尚未发布实际数据,因此我无法为您提供详细建议。我认为最好的办法是按顺序对类别进行编号,然后将该数字用作直方图中每个条形的“x”值。
| 归档时间: |
|
| 查看次数: |
729 次 |
| 最近记录: |