Search code examples
pythonbar-charthistogramprojectfinal

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


Solution

  • 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