plt.hist MatPlotlib中的bins选项

2024-10-02 10:25:34 发布

您现在位置:Python中文网/ 问答频道 /正文

enter image description here

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

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

以下是相关代码:

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

Tags: theindictionarybincountpltrandomresult
1条回答
网友
1楼 · 发布于 2024-10-02 10:25:34

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

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

import numpy as np
import matplotlib.pyplot as plt

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

enter image description here

在给定的柱状图上有6个箱子。问题是4个箱子合并成一个大箱子

enter image description here

相关问题 更多 >

    热门问题