1import numpy as np
2import scipy.special
3from bokeh.layouts import gridplot
4# 绘图函数
5def make_plot(title, hist, edges, x, pdf, cdf):
6 p = figure(title=title, tools='', background_fill_color="#fafafa")
7 p.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:],
8 fill_color="navy", line_color="white", alpha=0.5)
9 p.line(x, pdf, line_color="#ff8888", line_width=4, alpha=0.7, legend="PDF")
10 p.line(x, cdf, line_color="orange", line_width=2, alpha=0.7, legend="CDF")
11
12 p.y_range.start = 0
13 p.legend.location = "center_right"
14 p.legend.background_fill_color = "#fefefe"
15 p.xaxis.axis_label = 'x'
16 p.yaxis.axis_label = 'Pr(x)'
17 p.grid.grid_line_color="white"
18 return p
19# 正态分布
20mu, sigma = 0, 0.5
21measured = np.random.normal(mu, sigma, 1000)
22hist, edges = np.histogram(measured, density=True, bins=50)
23x = np.linspace(-2, 2, 1000)
24# 拟合曲线
25pdf = 1/(sigma * np.sqrt(2*np.pi)) * np.exp(-(x-mu)**2 / (2*sigma**2))
26cdf = (1+scipy.special.erf((x-mu)/np.sqrt(2*sigma**2)))/2
27p1 = make_plot("Normal Distribution (μ=0, σ=0.5)", hist, edges, x, pdf, cdf)
28# 对数正态分布
29mu, sigma = 0, 0.5
30measured = np.random.lognormal(mu, sigma, 1000)
31hist, edges = np.histogram(measured, density=True, bins=50)
32x = np.linspace(0.0001, 8.0, 1000)
33pdf = 1/(x* sigma * np.sqrt(2*np.pi)) * np.exp(-(np.log(x)-mu)**2 / (2*sigma**2))
34cdf = (1+scipy.special.erf((np.log(x)-mu)/(np.sqrt(2)*sigma)))/2
35p2 = make_plot("Log Normal Distribution (μ=0, σ=0.5)", hist, edges, x, pdf, cdf)
36# 伽玛分布
37k, theta = 7.5, 1.0
38measured = np.random.gamma(k, theta, 1000)
39hist, edges = np.histogram(measured, density=True, bins=50)
40x = np.linspace(0.0001, 20.0, 1000)
41pdf = x**(k-1) * np.exp(-x/theta) / (theta**k * scipy.special.gamma(k))
42cdf = scipy.special.gammainc(k, x/theta)
43p3 = make_plot("Gamma Distribution (k=7.5, θ=1)", hist, edges, x, pdf, cdf)
44# 韦伯分布
45lam, k = 1, 1.25
46measured = lam*(-np.log(np.random.uniform(0, 1, 1000)))**(1/k)
47hist, edges = np.histogram(measured, density=True, bins=50)
48x = np.linspace(0.0001, 8, 1000)
49pdf = (k/lam)*(x/lam)**(k-1) * np.exp(-(x/lam)**k)
50cdf = 1 - np.exp(-(x/lam)**k)
51p4 = make_plot("Weibull Distribution (λ=1, k=1.25)", hist, edges, x, pdf, cdf)
52# 显示
53show(gridplot([p1,p2,p3,p4], ncols=2, plot_width=400, plot_height=400
, toolbar_location=None))