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

30 投票
2 回答
110774 浏览
提问于 2025-04-17 19:07

我想根据我手头的样本画出一个概率密度函数的近似图,也就是一条能模仿直方图形状的曲线。我可以有任意大小的样本。

2 个回答

29

你需要做的是使用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) )

这个核密度可以根据需要进行配置,并且可以轻松处理多维数据。它还可以避免askewchan提供的图中看到的样条扭曲。

在这里输入图片描述

43

如果你想要绘制一个分布图,并且你已经知道这个分布的具体形式,可以把它定义成一个函数,然后按照这个函数来绘制:

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

你可以在调用 UnivariateSpline 函数时调整 s(平滑因子)的值,来增加或减少平滑效果。例如,使用这两个值你可以得到:

dist to func

撰写回答