【发布时间】:2020-02-29 17:07:11
【问题描述】:
您好,提前感谢您。我从一个熊猫数据框开始,我想制作一个带有趋势线的二维图,显示加权平均值 y 值和误差条,以表示平均值的不确定性。平均值应由每个 bin 中的事件总数加权。我首先将 df 分组为“光子”组和“总”组,其中“光子”是总数的子集。在每个箱中,我正在绘制光子事件与总数的比率。在 x 轴和 y 轴上,我有两个不相关的变量“簇能量”和“周长能量”。 我的尝试:
#make the 2d binning and total hist
energybins=[11,12,13,14,15,16,17,18,19,20,21,22]
ybins = [0,.125,.25,.5,.625,.75,1.,1.5,2.5]
total_hist,x,y,i = plt.hist2d(train['total_energy'].values,train['max_perimeter'].values,[energybins,ybins])
total_hist = np.array(total_hist)
#make the photon 2d hist with same bins
groups = train.groupby(['isPhoton'])
prompt_hist,x,y,i = plt.hist2d(groups.get_group(1)['total_energy'].values,groups.get_group(1)['max_perimeter'].values,bins=[energybins,ybins])
prompt_hist = np.array(prompt_hist)
ratio = np.divide(prompt_hist,total_hist,out=np.zeros_like(prompt_hist),where = total_hist!=0)
#plot the ratio
fig, ax = plt.subplots()
ratio=np.transpose(ratio)
p = ax.pcolormesh(ratio,)
for i in range(len(ratio)):
for j in range(len(ratio[i])):
text = ax.text(j+1, i+1, round(ratio[i, j], 2),ha="right", va="top", color="w")
ax.set_xticklabels(energybins)
ax.set_yticklabels(ybins)
plt.xlabel("Cluster Energy")
plt.ylabel("5x5 Perimeter Energy")
plt.title("Prompt Photon Fraction")
def myBinnedStat(x,v,bins):
means,_,_ = stats.binned_statistic(x,v,'mean',bins)
std,_ ,_= stats.binned_statistic(x,v,'std',bins)
count,_,_ = stats.binned_statistic(x,v,'count',bins)
return [ufloat(m,s/(c**(1./2))) for m,s,c in zip(means,std,count)]
然后我可以绘制误差条图,但我无法在与 pcolormesh 相同的轴上绘制误差条。我能够用 hist2d 做到这一点。我不确定为什么会这样。我觉得有一种更清洁的方式来完成整个事情。
【问题讨论】:
-
是否明确定义要在工作中绘制的轴:
ax.errorbar(...)? -
我尝试在我使用
ax.errorbar()绘制的绘图中添加一条线,它将两个图绘制在同一个图中,但接下来的两个是彼此的。有趣的是,如果我有一个 hist2d 而不是 pcolormesh 的底层图,它将起作用。也许这意味着 pcolormesh 不支持这个? @busybear -
也许您的 x 值在两个图之间不匹配?如果您提供您的输出,它可能会提供一些见解。
-
感谢您的回复,@busybear 我正在使用“energybins”向量来表示生成比率的 hist2ds 的 x 值和误差条图。我添加了一个截图
标签: python numpy matplotlib data-visualization seaborn