如何生成随机数的直方图?

3

我用以下代码生成了100个1到100之间的随机数:

def histogram():
    for x in range(100):
        x = random.randint(1, 100)
        print(x)

现在我正试图用直方图来表示这些信息,我导入了matplotlib.pyplot作为plt并尝试构建直方图,但好像遇到了问题。
我尝试过:
def histogram():
    for x in range(100):
        x = random.randint(1, 100)
        return x       
    histogram_plot = histogram()
    plt.hist(histogram_plot)
    plt.show()

我也尝试过:

def histogram():
    for x in range(100):
        x = random.randint(1, 100)
        print(x)
        plt.hist(x)
        plt.show()

我做错了什么?

那么你得到了什么? - vovaminiof
在循环内放置一个无条件的 return 意味着函数将在循环的一次迭代后返回。你真的不想这样做! - PM 2Ring
3个回答

6
这里有一个类似于你的代码的小示例,可以正常工作。
>>> import matplotlib.pyplot as plt
>>> import random
>>> data = [random.randint(1, 100) for _ in range(100)]
>>> plt.hist(data)
(array([ 15.,  13.,   9.,   9.,  11.,   9.,   9.,  11.,   6.,   8.]),
 array([   1. ,   10.9,   20.8,   30.7,   40.6,   50.5,   60.4,   70.3,   80.2,   90.1,  100. ]),
 <a list of 10 Patch objects>)
>>> plt.show()

您遇到的问题在于您的直方图函数。您在每次迭代中将变量x重新分配为随机的int,而不是构建一个随机值的列表

输入图像描述


1
这是一个漂亮的例子,展示了指数分布、正态分布和泊松分布随机数的直方图。
import numpy as np
import matplotlib.pyplot as plt 
import seaborn as sns

sns.set(style="whitegrid")
np.random.seed(10)

fig, axs=plt.subplots(1, 3, figsize=(15, 6))
axs[0].hist(np.random.exponential(scale = 10, size = 10000), color = "r")
axs[0].set_title("Exponentially")

axs[1].hist(np.random.randn(10000), color = "m") 
axs[1].set_title("Normally")

axs[2].hist(np.random.poisson(lam = 5, size = 10000), color = "k")
axs[2].set_title("Poisson")

plt.show()

enter image description here


1
在第一个函数中,你在循环中使用了return,因此结果永远不会被绘制,因为解释器永远不会达到绘图代码。在你的第二个示例中,你迭代每个实例并每次绘制一个实例。
简单地创建一个随机数列表并将其绘制出来:
def histogram():
    xs = [random.randint(1, 100) for _ in range(100)]
    print(x)
    plt.hist(xs)
    plt.show()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接