【发布时间】:2019-12-15 21:00:33
【问题描述】:
在下面的代码中,我生成随机数,然后获取概率并创建图形。现在我怎样才能制作两次图表,就像我想再次生成随机数并再次创建图表一样。
#!/usr/bin/env python3
from collections import Counter
import numpy as np
import matplotlib.pyplot as plt
#Random Number Generating
x = np.random.randint(low=1, high=100, size=100000)
counts = Counter(x)
total = sum(counts.values())
d1 = {k:v/total for k,v in counts.items()}
grad = d1.keys()
prob = d1.values()
print(str(grad))
print(str(prob))
#bins = 20
plt.hist(prob,bins=20, normed=1, facecolor='blue', alpha=0.5)
#plt.plot(bins, hist, 'r--')
plt.xlabel('Probability')
plt.ylabel('Number Of Students')
plt.title('Histogram of Students Grade')
plt.subplots_adjust(left=0.15)
plt.show()
【问题讨论】:
-
把所有东西都放到一个函数中。调用该函数两次。 (你想得到相同的随机数,还是不同的?)
-
如果你想重现精确的图形——为随机数生成器设置一个明确的种子。看到这个:docs.scipy.org/doc/numpy-1.15.1/reference/generated/…
-
@ImportanceOfBeingErnest 我从不在 python 中使用函数。你能把这段代码放在函数中吗?并且相同的数字或生成随机数无关紧要。
-
@JohnColeman 我如何在我的代码中调用这个
numpy.random.seed(seed=None)?
标签: python python-3.x matplotlib histogram