python – 显示具有非常不均匀的bin宽度的直方图
发布时间:2020-12-20 11:46:43 所属栏目:Python 来源:网络整理
导读:这是直方图 为了生成这个图,我做了: bins = np.array([0.03,0.3,2,100])plt.hist(m,bins = bins,weights=np.zeros_like(m) + 1. / m.size) 但是,正如您所注意到的,我想绘制每个数据点的相对频率的直方图,只有3个不同大小的区间: bin1 = 0.03 – 0.3 bin2 =
这是直方图
为了生成这个图,我做了: bins = np.array([0.03,0.3,2,100]) plt.hist(m,bins = bins,weights=np.zeros_like(m) + 1. / m.size) 但是,正如您所注意到的,我想绘制每个数据点的相对频率的直方图,只有3个不同大小的区间: bin1 = 0.03 – > 0.3 bin2 = 0.3 – > 2 bin3 = 2 – > 100 由于最后一个bin的大小相对于其他bin非常大,因此直方图看起来很难看.如何修复直方图?我想改变箱子的宽度,但我不想改变每个箱子的范围. 解决方法
正如@cel指出的那样,这不再是直方图,但你可以用plt.bar和np.histogram来做你想要的.然后,您只需将xticklabels设置为描述bin边缘的字符串.例如:
import numpy as np import matplotlib.pyplot as plt bins = [0.03,100] # your bins data = [0.04,0.07,0.1,0.2,0.8,1,1.5,4,5,7,8,43,45,54,56,99] # random data hist,bin_edges = np.histogram(data,bins) # make the histogram fig,ax = plt.subplots() # Plot the histogram heights against integers on the x axis ax.bar(range(len(hist)),hist,width=1) # Set the ticks to the middle of the bars ax.set_xticks([0.5+i for i,j in enumerate(hist)]) # Set the xticklabels to a string that tells us what the bin edges were ax.set_xticklabels(['{} - {}'.format(bins[i],bins[i+1]) for i,j in enumerate(hist)]) plt.show() 编辑 如果您更新到matplotlib v1.5.0,您会发现该栏现在需要一个kwarg tick_label,这可以使这个绘图更容易(see here): hist,bins) ax.bar(range(len(hist)),width=1,align='center',tick_label= ['{} - {}'.format(bins[i],j in enumerate(hist)]) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |