使用matplotlib通过样本绘制概率密度函数 [英] Plotting probability density function by sample with matplotlib

查看:1459
本文介绍了使用matplotlib通过样本绘制概率密度函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to plot an approximation of probability density function based on a sample that I have; The curve that mimics the histogram behaviour. I can have samples as big as I want.

推荐答案

如果您想绘制一个分布,并且知道它,请将其定义为一个函数,并按以下方式绘制:

If you want to plot a distribution, and you know it, define it as a function, and plot it as so:

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


如果您没有精确的分布作为分析函数,也许您可​​以生成一个大样本,进行直方图处理,并以某种方式使数据平滑:


If you don't have the exact distribution as an analytical function, perhaps you can generate a large sample, take a histogram and somehow smooth the data:

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(平滑因子),以增大或减小平滑度.例如,使用两者,您将获得:

You can increase or decrease s (smoothing factor) within the UnivariateSpline function call to increase or decrease smoothing. For example, using the two you get:

这篇关于使用matplotlib通过样本绘制概率密度函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆