python – 显示具有非常不均匀的bin宽度的直方图

这是直方图

《python – 显示具有非常不均匀的bin宽度的直方图》

为了生成这个图,我做了:

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,0.3,2,100] # your bins
data = [0.04,0.07,0.1,0.2,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()

《python – 显示具有非常不均匀的bin宽度的直方图》

编辑

如果您更新到matplotlib v1.5.0,您会发现该栏现在需要一个kwarg tick_label,这可以使这个绘图更容易(see here):

hist, bin_edges = np.histogram(data,bins)

ax.bar(range(len(hist)),hist,width=1,align='center',tick_label=
        ['{} - {}'.format(bins[i],bins[i+1]) for i,j in enumerate(hist)])
点赞