DENESHA MCINTOSH
DENESHA MCINTOSH

Reputation: 21

How to create a histogram in python

Repeatedly rolling a die would result in a uniform distribution of values between 1 and 6, inclusive. Repeatedly rolling 2 dice would result in a uniform distribution of values between 2 and 12, inclusive. In this simulation, repeatedly roll 6 dice and count the number of occurrences of each value: i. After 1000 simulations. ii. After 100,000 simulation. Plot the result using Matplotlib I am having issues generating the values to plot on the histogram

import random

# Set the number of dice rolls
num_rolls = 100

# Create a dictionary to track the number of occurrences of each value
occurrences = {}

# Roll the dice num_rolls times
for i in range(num_rolls):
    # Generate a random value between 6 and 36
    value = random.randint(6, 36)

    # Increment the count for this value in the dictionary
    if value in occurrences:
        occurrences[value] += 1
    else:
        occurrences[value] = 1

# Print the number of occurrences of each value
for value in occurrences:
    print(f"Total dice per roll {value}: Number of rolls {occurrences[value]}")

import matplotlib.pyplot as plt


# Plot the results
plt.bar(value, occurrences[value])
plt.xlabel('Value of roll')
plt.ylabel('Number of occurrences')
plt.title('Results of rolling 6 dice 100 times')
plt.show()

Upvotes: 1

Views: 474

Answers (3)

The Photon
The Photon

Reputation: 1367

plt.bar(value, occurrences[value])

When you get to this line, value is not an array or list, it's only a single value (the last key of the occurences dict that you printed out in a previous line).

So you're printing out a bar chart with only a single bar in it, not a bar for each of the possible values that can be thrown by the dice.

You also have some other issues to watch out for:

  • A dict doesn't keep its keys in order. You probably want to plot out your bar chart with the value 0 on the left side and 36 on the right. You'll need to sort your values (and their occurrences) before you plot them. Or change your datastructures so that they are kept in order from the beginning.

  • You didn't simulate throwing six dice and adding up their values. Instead you simulated throwing a single 30-sided die. You're going to see a roughly uniform distribution of occurrences for each value between 6 and 36, which isn't the same distribution you'd get by adding up the values of six 6-sided dice.

I would propose something like this:

import numpy as np

def throw_6():
    # Generate 6 random numbers between 1 and 6 and sum them together:
    return sum([random.randint(1,6) for _ in range(6)])

# Set the number of dice rolls
num_rolls = 100_000

# An array for the x-axis of the graph, giving all the possible results of summing 6 die rolls:
all_values = np.arange(6, 37)

# An array to track the number of occurrences of each value, initialized to 0
# occurrences[0] thru occurrences[5] will never be used, but the wasted space is worth it to make the rest of the code more readable: 
occurrences = np.zeros(37)

# Roll the dice num_rolls times
for i in range(num_rolls):
    # Simulate throwing 6 dice and taking the sum:
    value = throw_6()
    occurrences[value] += 1

# Print the number of occurrences of each value
for value in all_values:
    print(f"Total dice per roll {value}: Number of rolls {occurrences[value]}")

# Plot the results
plt.bar(all_values, occurrences[6:37])
plt.xlabel('Value of roll')
plt.ylabel('Number of occurrences')
plt.title(f'Results of rolling 6 dice {num_rolls} times')
plt.show()

Result:

enter image description here

Upvotes: 2

Alexander L. Hayes
Alexander L. Hayes

Reputation: 4273

The occurrences dictionary contains keys representing dice combinations (6-36), and values representing the number of times that number came up.

Therefore you can make a bar plot of the keys vs. the values:

plt.bar(occurrences.keys(), occurrences.values())
plt.show()

histogram showing results of rolling 6 dice 100 times. x axis shows numbers 6-36, y axis shows number of occurrences 0 through 9.

Upvotes: 1

Bhargav
Bhargav

Reputation: 4062

Ahh you almost there. You are printing only for last values. you have to take a list and append each & everyone of them.

vals =[]
occ =[]

inside loop

vals.append(value)
occ.append(occurrences[value])

complete code

import random

# Set the number of dice rolls
num_rolls = 100

vals =[]
occ =[]



# Create a dictionary to track the number of occurrences of each value
occurrences = {}

# Roll the dice num_rolls times
for i in range(num_rolls):
    # Generate a random value between 6 and 36
    value = random.randint(6, 36)

    # Increment the count for this value in the dictionary
    if value in occurrences:
        occurrences[value] += 1
    else:
        occurrences[value] = 1

# Print the number of occurrences of each value
for value in occurrences:
    print(f"Total dice per roll {value}: Number of rolls {occurrences[value]}")
    vals.append(value)
    occ.append(occurrences[value])

import matplotlib.pyplot as plt


# Plot the results
plt.bar(vals,occ)
plt.xlabel('Value of roll')
plt.ylabel('Number of occurrences')
plt.title('Results of rolling 6 dice 100 times')
plt.show()

output # enter image description here

Upvotes: 2

Related Questions