简体   繁体   中英

why does my histogram look weird in this stochastic problem plot in python?

I am trying to write a stochastic program in Python to replicate a fair dice (one dice) roll, such that this one dice is rolled 100 times. I intend to display the output of the dice rolls as a histogram.

I thought histograms had a specific n shape but this is what I have been getting with the code I used below.

import numpy as np
import matplotlib.pyplot as plt
x = []
for i in range(100):
    num1 = random.choice(range(1,7))
    x.append(num1)
plt.hist(x, bins=6)
plt.xlabel('dice')
plt.show()

myweirdhistogram

Also, is there an easier way to plot a histogram in python when you have, eg ages as [10,3,5,1] and the frequency in a table as [2,3,4,4]? Do I have to type out the entire frequency of the ages in a list like this: age = [10,10,3,3,3,5,5,5,5,1,1,1,1] before I write the program? please see what I mean in the code below:

import numpy as np
import matplotlib.pyplot as plt

plt.close()

ages = [88,88,88,88,76,76,76, 65,65,65,65,65,96,96,52,52,52,52,52,98,98,102,102,102,102]

#the frequency was = [4, 3, 5, 2, 5, 2, 4] which corresponded to the ages [88,76,65,96,52,98,102]

num_bins = 25
n, bins, patches = plt.hist(ages, num_bins, facecolor='blue')

plt.xlabel('age')
plt.ylabel('Frequency of occurence')
plt.show()

#my histogram again looks more like a bar chart. Is this because I used bins as the ages?

So far, its easier to plot a histogram with random numbers but not a table for me. Here is my second weird output: mysecondweirdhistogram

>>> ages = [10,3,5,1]
>>> freqs = [2,3,4,4]

Use zip to pair each age with it's frequency; then use the frequency to add that many to a new container.

>>> q = []
>>> for a, f in zip(ages, freqs):
...     q.extend(a for _ in range(f))

>>> q
[10, 10, 3, 3, 3, 5, 5, 5, 5, 1, 1, 1, 1]
>>>

a for _ in range(f) is a generator expression which will produce f a 's when iterated. The extend method consumes (iterates over) the generator expression. We typically use _ for values that we aren't going to use.

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