使用matplotlib通过样本绘制概率密度函数

时间:2013-03-14 16:53:28

标签: python matplotlib histogram probability

我想绘制基于概率密度函数的近似值 我有一个样本;模拟直方图行为的曲线。我可以 有我想要的样本。

2 个答案:

答案 0 :(得分:31)

如果您想绘制分布,并且您知道它,请将其定义为函数,并将其绘制为:

import numpy as np
from matplotlib import pyplot as plt

def my_dist(x):
    return np.exp(-x ** 2)

x = np.arange(-100, 100)
p = my_dist(x)
plt.plot(x, p)
plt.show()

如果你没有确切的分布作为分析函数,也许你可以生成一个大样本,采用直方图并以某种方式平滑数据:

import numpy as np
from scipy.interpolate import UnivariateSpline
from matplotlib import pyplot as plt

N = 1000
n = N//10
s = np.random.normal(size=N)   # generate your data sample with N elements
p, x = np.histogram(s, bins=n) # bin it into n = N//10 bins
x = x[:-1] + (x[1] - x[0])/2   # convert bin edges to centers
f = UnivariateSpline(x, p, s=n)
plt.plot(x, f(x))
plt.show()

您可以在s函数调用中增加或减少UnivariateSpline(平滑因子)以增加或减少平滑。例如,使用这两个: dist to func

答案 1 :(得分:23)

您需要做的是使用scipy.stats.kde包中的gaussian_kde。

根据您的数据,您可以执行以下操作:

from scipy.stats.kde import gaussian_kde
from numpy import linspace
# create fake data
data = randn(1000)
# this create the kernel, given an array it will estimate the probability over that values
kde = gaussian_kde( data )
# these are the values over wich your kernel will be evaluated
dist_space = linspace( min(data), max(data), 100 )
# plot the results
plt.plot( dist_space, kde(dist_space) )

可以随意配置内核密度,并且可以轻松处理N维数据。 它还可以避免你在askewchan给出的图中看到的样条扭曲。

enter image description here

相关问题