【问题标题】:How to plot histogram of counts per range that each bin is labeled with a interval range?如何绘制每个 bin 标有区间范围的每个范围的计数直方图?
【发布时间】:2019-12-28 01:18:35
【问题描述】:

我有一个 python 目录,其中的键存储百分比范围:0_5、5_10、10_15、....80_85、85_90、90_95、95_100。每个键的值是整个数据中的计数。我想用 matplotlib 绘制一个直方图来查看它的分布,会有 20 个 bin,每个 bin 都应该标有它的百分比范围,每个 bin 之间会有一点间距,以便它们分开。

我试过这段代码,它给了我有 20 个 bin 的直方图。但这不是我需要的。

commutes = pd.Series(counts)
commutes.plot.hist(grid = False, bins = 20, rwidth = 0.8, color = 'tomato', edgecolor='gray', label = 'Type 1')

另外,我试过这个,它显示错误:ValueError: weights should have the same shape as x

pylab.hist(ratio.keys(), weights = ratio.values(), bins=range(20))

这就是我创建目录的方式。变量计数存储 700 个百分比值的列表。

for i in range(0,100,5):
    start = i
    end = i+5
    key = str(start)+"_"+str(end)
    number = 0
    for count in counts:
        if((count >= start) and (count < end)):
            number = number + 1
    ratio[key] = number

【问题讨论】:

    标签: python matplotlib histogram


    【解决方案1】:

    ratio.keys()ratio.values() 的类型为 dict_keysdict_values。我猜 matplotlib 正在尝试将 np.array()np.asarray() 应用于它们,这不能按预期工作,即它被转换为 array(dict_keys([...]), dtype=object) 而不是数字数组。

    一个简单的解决方法是首先将字典键和值转换为列表。

    pylab.hist(list(ratio.keys()), weights=list(ratio.values()), bins=range(len(ratio)))
    

    【讨论】:

    • 我尝试了紧凑的语法来计算计数并且它有效。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2016-11-05
    • 2016-05-05
    • 1970-01-01
    • 2014-09-21
    • 2018-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多