簡體   English   中英

如何在 python 中創建直方圖

[英]How to create a histogram in python

重復擲骰子會導致值在 1 到 6 之間均勻分布,包括端值。 重復滾動 2 個骰子將導致值在 2 到 12 之間均勻分布,包括端值。 在這個模擬中,重復擲 6 個骰子並計算每個值出現的次數: i。 經過 1000 次模擬。 二. 經過 100,000 次模擬。 Plot 結果使用 Matplotlib 我在直方圖上生成 plot 的值時遇到問題

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

啊,你快到了。 您僅打印最后一個值。 你必須拿一份清單和 append 每個人。

vals =[]
occ =[]

內循環

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

完整代碼

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# 在此處輸入圖像描述

occurrences字典包含表示骰子組合 (6-36) 的鍵和表示該數字出現次數的值。

因此,您可以制作鍵與值的 plot 條:

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

直方圖顯示擲 6 個骰子 100 次的結果。 x 軸顯示數字 6-36,y 軸顯示出現次數 0 到 9。

plt.bar(value, occurrences[value])

當您到達這一行時, value不是數組或列表,它只是一個值(您在上一行中打印出的occurences dict 的最后一個鍵)。

因此,您正在打印一個條形圖,其中只有一個條形圖,而不是一個條形圖,表示每個可能的值都可以由骰子拋出。

您還需要注意其他一些問題:

  • 字典不會按順序保留其鍵。 您可能想要 plot 出您的條形圖,左側值為 0,右側值為 36。 在 plot 它們之前,您需要對值(及其出現次數)進行排序。

  • 您沒有模擬擲六個骰子並將它們的值相加。 相反,您模擬投擲一個 30 面的骰子。 您將看到 6 到 36 之間的每個值的出現次數大致均勻分布,這與將六個 6 面骰子的值相加得到的分布不同。

我會提出這樣的建議:

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

結果:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM