在 matplotlib (pandas) X 和 Y 轴规范中绘制直方图

时间:2021-08-01 20:22:08

标签: python pandas matplotlib histogram probability

对于六面骰子的滚动,我需要随机模拟该事件 50 次,并在使用数量 = 6 时为骰子上的每个数字绘制结果直方图

我尝试了以下方法:

import random
 
test_data = [0, 0, 0, 0, 0, 0] 
n = 50 

for i in range(n):
  result = random.randint(1, 6)
  test_data[result - 1] = test_data[result - 1] + 1

plt.hist(test_data,bins=6)

有没有办法在 x 轴上绘制骰子的数量,并在 y 轴上绘制骰子上每个数字的结果?

1 个答案:

答案 0 :(得分:0)

对于您想要做的事情,我认为使用条形图更正确,因为不同的可能结果(X 轴)不是频率。那么,为了您的目的,我认为最好使用字典做这样的事情:

import random
from matplotlib import pyplot as plt
 
test_data = {"1":0, "2":0, "3":0, "4":0, "5":0, "6":0}
n = 50 

for i in range(n):
  result = random.randint(1, 6)
  test_data[str(result)] += 1

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

这应该可以解决问题。希望有帮助!