简体   繁体   中英

How do I generate a histogram of random numbers?

I generated 100 random numbers between 1 and 100 with code:

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

Now I am trying to represent this information in a histogram, I imported matplotlib.pyplot as plt and tried to construct this but I seem to be encountering problems.

I tried:

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

and I also tried:

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

What am I doing wrong?

Here is a small working example that is similar to your code

>>> 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()

在此处输入图片说明

The issue you are having is in your histogram function. You are re-assigning the variable x to a random int every iteration, rather than building up a list of random values.

In the first function, you return in a loop, so the result will never get plotted since the interpreter will never reach the plot code. In you second example you iterate and each time plot a single instance.

Simply create a list of random numbers and plot them:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM