1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import binom
def runplt(n: int, p: float, ax: plt.axes, fmt='yo', color='grey'):
'''
绘制单个二项分布的准备工作
'''
x = np.arange(n)
y = [binom.pmf(x, n, p) for x in x]
ax.plot(x, y, fmt, ms=5, mec='black', label='p={}\nn={}'.format(p, n))
ax.vlines(x, 0, y, lw=5, color=color, alpha=0.5)
ax.vlines(x, 0, y, lw=1, color=color)
ax.set_xticks([x for x in range(0, n + 2, 2)])
ax.legend(loc='best')
def main():
'''
绘制一组二项分布:参数对比
'''
# 参数
ns = np.array([[10, 10, 10],
[10, 15, 20]])
ps = np.array([[0.1, 0.5, 0.7],
[0.5, 0.5, 0.5]])
# 绘图
nrows = 2
ncols = 3
fig, axes = plt.subplots(nrows, ncols, figsize=(14, 7), sharey=True)
for i in range(nrows):
for j in range(ncols):
runplt(ns[i, j], ps[i, j], axes[i, j])
fig.suptitle('PMF of Binomial Distribution')
plt.savefig('PMF-of-Binomial-distribution.svg')
plt.show()
if __name__ == '__main__':
main()
|