python – 将值放在bin的中心以获得直方图

python – 将值放在bin的中心以获得直方图,第1张

概述我有以下代码来绘制直方图. time_new中的值是发生事件的小时数. time_new=[9, 23, 19, 9, 1, 2, 19, 5, 4, 20, 23, 10, 20, 5, 21, 17, 4, 13, 8, 13, 6, 19, 9, 14, 9, 10, 23, 19, 23, 20, 19, 6, 5, 24, 20, 19, 15, 14, 19, 14, 15, 21] 我有以下代码来绘制直方图. time_new中的值是发生事件的小时数.

time_new=[9,23,19,9,1,2,5,4,20,10,21,17,13,8,6,14,24,15,21]    hour_List = time_new    print hour_List    numbers=[x for x in xrange(0,24)]    labels=map(lambda x: str(x),numbers)    plt.xticks(numbers,labels)    plt.xlim(0,24)    pdb.set_trace()    plt.hist(hour_List,bins=24)    plt.show()

这会产生直方图,但是这些箱子没有按照我的意愿对齐.我希望小时位于垃圾箱的中心,而不是边缘.

我提到了this question / answer,但似乎也没有回答这个问题.

我尝试使用以下代码来代替直方图,但它没有为值23绘制条形图

plt.hist(hour_List,bins=np.arange(24)-0.5)

任何人都可以帮助我获得24个垃圾箱,每个小时的中心位置?

解决方法 要获得24个箱,您需要在序列中定义25个值来定义箱边. n个箱子总是有n个1个边缘.

所以,改变你的路线

plt.hist(hour_List,bins=np.arange(24)-0.5)

plt.hist(hour_List,bins=np.arange(25)-0.5)

注意 – 您的测试数据应包含两个边缘情况.如果您只是通过舍入来提取小时数,则列表中应该有一些0值.

完整示例:

import matplotlib.pyplot as pltimport numpy as npdef plot_my_time_based_histogram():    #Note - changed the 24 values for 0    time_new=[9,21]    fig,ax = plt.subplots()    hour_List = time_new    print hour_List    numbers=[x for x in xrange(0,labels)    #Make limit slightly lower to accommodate wIDth of 0:00 bar    plt.xlim(-0.5,24)    plt.hist(hour_List,bins=np.arange(25)-0.5)    # Further to comments,OP wants arbitrary labels too.    labels=[str(t)+':00' for t in range(24)]    ax.set_xticklabels(labels)    plt.show()plot_my_time_based_histogram()

结果:

总结

以上是内存溢出为你收集整理的python – 将值放在bin的中心以获得直方图全部内容,希望文章能够帮你解决python – 将值放在bin的中心以获得直方图所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/langs/1193445.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存