【问题标题】:Drawing a histogram using matplot.lib使用 matplotlib 绘制直方图
【发布时间】:2016-06-09 05:34:30
【问题描述】:

我正在尝试使用 marplot.lib 库在 Python 中绘制直方图;但是,我不断收到此错误:“AttributeError: bins must increase monotonically.”

这是我目前的代码:

def draw_viz(info):
    stars = [tup[0] for tup in info]
    scores = [tup[1] for tup in info]

    plt.hist(range, scores)
    plt.show()

传入的参数是info。 Info 是一个元组列表,可能如下所示:

[(4, 0.7984031936127745), (5, 0.5988023952095809), (5, 0.8739076154806492), (5, 0.7364544976328248), (3, 0.9980039920159681), (1, 0.8455034588777863), (4, 0.6659267480577137), (5, 0.9950248756218907), (5, 0.9991673605328892), (3, 0.5828476269775188), (1, 0.5226084980686208), (1, 0.5291005291005291), (4, 0.7984031936127745), (4, 0.5380476556495004), (5, 0.6357856494096277), (2, 0.9975062344139651), (4, 0.6644518272425249)]

我的范围限制为 1、2、3、4 或 5。 分数介于 0 和 1 之间。

我想绘制一个可以处理我传入的内容的直方图,但我真的不确定该怎么做,甚至不知道如何为这个初始化 bin...

任何帮助将不胜感激!

【问题讨论】:

标签: python matplotlib histogram


【解决方案1】:

您忘记将值传递给 range 参数(这不是必需的)。数据本身是完全有效的。下面的代码应该给你一个粗略的图表:

plt.hist(stars, bins=5)
plt.show()

为了更好看,也许:

plt.hist(stars, bins=np.arange(6)+0.5)
plt.xticks(range(1,6))
plt.xlim([0.5,5.5])
plt.show()

进一步参考:

【讨论】:

    【解决方案2】:

    您得到的参数顺序错误hist 首先需要数据,然后是可选的一些 bin 或 bin 边缘列表。在你的情况下,我会这样做

    plt.hist(stars,[0.5,1.5,2.5,3.5,4.5,5.5])
    plt.show()
    
    plt.hist(scores)
    plt.show
    

    【讨论】: