plt.hist MatPlotlib 中的 bins 选项

bins option in plt.hist MatPlotlib

尽管在 matplotlib.pyplot.hist() 的 'bins=' 选项中指定了 6 个 bin,但在上面的直方图中有 5 个 bin。我认为 'bins=' 应该强制程序绘制指定数量的 bin。

如果有人能澄清,将不胜感激。

这是相关代码:

import random
def simulate_diceRolls():
    count_dice_faces=[0, 0, 0, 0, 0, 0] 
    n = 1000 
    for i in range(n):
      result = random.randint(1, 6)
      count_dice_faces[result - 1] = count_dice_faces[result - 1] + 1

    simulation_dictionary = dict()
    for i in range(len(count_dice_faces)):
        simulation_dictionary[i+1] = count_dice_faces[i]

    plt.hist(count_dice_faces,bins=6)
    print(count_dice_faces)
    #the following code plots a nicer looking hisotgram but does not satisfy the using 'bin='
    #requirement in the question
    #plt.bar(simulation_dictionary.keys(), simulation_dictionary.values(), width=1,color='g',ec='black')
    plt.show()
simulate_diceRolls()

bins 参数指定数据将被拆分到的框数。您可以将其指定为整数或 bin 边缘的列表。

例如,这里我们请求 20 个箱子:

import numpy as np
import matplotlib.pyplot as plt

x = np.random.randn(1000)
plt.hist(x, bins=20)

给定的直方图上有 6 个 bin。问题是 4 个箱子合并成了一个大箱子。