Skip to main content
 首页 » 编程设计

python之如何使用Python通过使用dataFrame中的某列数据绘制正态概率图

2025年05月04日22dflying

我有一个数据框,其中包含名为“每年千美元”和“雇员”的两列。

我通过计算 df['thousands of dollars per year'] 中的数据在此数据框中创建一个名为“cubic_Root”的新变量

df['cubic_Root'] = -1 / df['thousands of dollars per year'] ** (1. / 3) 

df['cubic_Root'] 中的数据是这样的:

ID cubic_Root

1 -0.629961

2 -0.405480

3 -0.329317

4 -0.480750

5 -0.305711

6 -0.449644

7 -0.449644

8 -0.480750

现在!如何使用 df['cubic_Root'] 中的数据绘制正态概率图。

请您参考如下方法:

您需要“概率”图。

因此对于单个图,您会得到如下所示的内容。

import scipy.stats 
import numpy as np 
import matplotlib.pyplot as plt 
 
# 100 values from a normal distribution with a std of 3 and a mean of 0.5 
data = 3.0 * np.random.randn(100) + 0.5 
 
counts, start, dx, _ = scipy.stats.cumfreq(data, numbins=20) 
x = np.arange(counts.size) * dx + start 
 
plt.plot(x, counts, 'ro') 
plt.xlabel('Value') 
plt.ylabel('Cumulative Frequency') 
 
plt.show() 

如果你想绘制一个分布,并且你知道它,将它定义为一个函数,然后这样绘制它:

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(平滑因子)以增加或减少平滑。例如,使用你得到的两个:

事件到达间隔时间的概率密度函数 (PDF)。

import numpy as np 
import scipy.stats 
 
# generate data samples 
data = scipy.stats.expon.rvs(loc=0, scale=1, size=1000, random_state=123) 

然后可以通过简单地调用获得核密度估计

scipy.stats.gaussian_kde(data,bw_method=bw) 

其中 bw 是估计过程的(可选)参数。对于这个数据集,考虑 bw 的三个值,拟合如下所示

# test values for the bw_method option ('None' is the default value) 
bw_values =  [None, 0.1, 0.01] 
 
# generate a list of kde estimators for each bw 
kde = [scipy.stats.gaussian_kde(data,bw_method=bw) for bw in bw_values] 
 
 
# plot (normalized) histogram of the data 
import matplotlib.pyplot as plt  
plt.hist(data, 50, normed=1, facecolor='green', alpha=0.5); 
 
# plot density estimates 
t_range = np.linspace(-2,8,200) 
for i, bw in enumerate(bw_values): 
    plt.plot(t_range,kde[i](t_range),lw=2, label='bw = '+str(bw)) 
plt.xlim(-1,6) 
plt.legend(loc='best') 

引用:

Python: Matplotlib - probability plot for several data set

how to plot Probability density Function (PDF) of inter-arrival time of events?