python – 将值放在bin的中心以获得直方图
发布时间:2020-12-20 11:45:01 所属栏目:Python 来源:网络整理
导读:我有以下代码来绘制直方图. 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(
我有以下代码来绘制直方图. 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 plt import numpy as np def 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() 结果: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |