Python绘制直方图时如何将区间外数据归入最外侧bin?
直方图区间外数据归入两端bin的解决方案
核心实现逻辑是提前对输入数据做截断处理,无需修改原有bin设置、绘图逻辑,就能把超出范围的数据分别归入最左、最右侧bin。
具体实现步骤
- 先计算你预设的直方图区间边界
- 对原始数据做截断:所有小于左边界的数值替换为左边界,所有大于等于右边界的数值替换为略小于右边界的值(适配直方图左闭右开的统计规则)
- 用处理后的数据生成直方图即可
可直接复用的修改后代码
#sort out N by histogram import numpy as np # 若已导入可删除该行 binwidth = 2.5*sig_Q low_center = min(Q_exp) + binwidth def set_range(first_bin = low_center, bin_width = binwidth, Nbins = 10): """ helper function to set the range and bin width input : first_bin = bin_center of the first bin, bin_width = the bin width, Nbins = total number of bins returns: a tuple that you can use in the range key word when defining a histogram. NOTE: for the histogram use the same number of bins: example: h = histo( r, range = set_range(-5., 1, 11), bins = 11) this created a histogram where the first bin is centered at -5. , the next at -4. etc. a total of 11 bins are created and the bin center of the last one is at 5. = first_bin + (Nbins-1)*bin_width """ rmin = first_bin - bin_width/2. rmax = rmin + Nbins*bin_width return (rmin,rmax) # -------------------新增修改部分开始------------------- hist_range = set_range(low_center, bin_width=binwidth, Nbins=10) rmin, rmax = hist_range # 截断数据,极小偏移量避免右边界点被丢弃,数值远小于bin宽不影响统计结果 Q_exp_clipped = np.clip(Q_exp, rmin, rmax - 1e-12) # 无numpy环境可替换为以下代码: # Q_exp_clipped = [max(rmin, min(x, rmax - 1e-12)) for x in Q_exp] # -------------------新增修改部分结束------------------- h = B.histo(Q_exp_clipped, range = hist_range, bins = 10) hx = h.bin_center hy = h.bin_content B.pl.ylabel("Counts", fontsize = 20) B.pl.xlabel("Gaussian Deviates", fontsize = 20) B.pl.title("Monte Carlo Millikan Oil-Drop Simulation", fontsize = 22) h.plot() B.pl.show()
补充说明
- 原有bin的中心位置、宽度、数量均未发生变化,不影响直方图的展示逻辑
- 1e-12的偏移量可根据你的数据精度调整,只要远小于bin宽度即可,避免对统计结果产生干扰
内容的提问来源于stack exchange,提问作者Valuska
相关产品推荐
相关产品推荐

