如何在此代码中两次生成随机数?

时间:2019-12-15 21:00:33

标签: python python-3.x matplotlib histogram

在下面的代码中,我生成随机数,然后采用概率创建图表。现在我该如何制作两次图形,就像我想再次生成随机数并再次创建图形一样。

#!/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()

1 个答案:

答案 0 :(得分:1)

您可以根据需要任意调用该函数!

import numpy as np
import matplotlib.pyplot as plt
from collections import Counter

def my_funct():
   np.random.seed(1223) # fixing the seed! but I don't think you need it

   #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()
#calling the function twice
my_funct()
my_funct()