有人可以帮我弄清楚为什么误差线与线直方图相比有点偏移?我希望在每个直方图条的中心都有误差条。
#mc and data are two dataframes.
norm = np.empty_like(mc['variable'])
bins=np.linspace(0,30,101)
binw=bins[1]-bins[0]
xc = bins[1:]-binw*0.5
hist_mc_corr,_ = np.histogram(mc['variable'].values, density=False, weights=mc['weight_mc'].values, bins=bins)
hist_data,_ = np.histogram(data['variable'].values, density=False, weights=data['weight_data'].values, bins=bins)
norm.fill(hist_data.sum()/hist_mc_corr.sum() )
plt.hist(mc['variable'], bins=100, range=(0, 30),histtype='step', weights=norm*mc['weight_mc'],)
(_, caps, _) = plt.errorbar(xc+binw*0.5, hist_data,ls='None', yerr=np.sqrt(hist_data), xerr=np.ones_like(hist_data)*binw*0.5,
color='black', label='data', marker='.')
for cap in caps:
cap.set_markeredgewidth(0)
虽然它应该看起来像(除了我不想用颜色填充直方图。)
非常感谢!
答案 0 :(得分:0)
您的错误栏会向右移动,因为您在
中明确地这样做了... plt.errorbar(xc+binw*0.5, ...
将binw*0.5
添加到xc
。
bins[:10]
array([ 0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.1, 2.4, 2.7])
xc[:10]
array([ 0.15, 0.45, 0.75, 1.05, 1.35, 1.65, 1.95, 2.25, 2.55, 2.85])
(xc+binw*0.5)[:10]
array([ 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.1, 2.4, 2.7, 3. ])
默认情况下,plt.hist
会在条形边缘之间居中绘制条形图(或您的案例中的步骤),因此您需要xc
处的错误栏:
... plt.errorbar(xc, ...