带加权平均趋势线的Python 2d比率图

2024-05-15 22:48:52 发布

您现在位置:Python中文网/ 问答频道 /正文

您好,提前谢谢。我从熊猫数据框开始,我想做一个2d图,用趋势线显示加权平均值,用误差条表示平均值的不确定性。平均值应根据每个箱子中的事件总数进行加权。我首先将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)]

然后我可以绘制一个errorbar图,但我无法在与pcolormesh相同的轴上绘制errorbar。我可以用hist2d做这个。我不知道这是为什么。我觉得有一种更干净的方法来做这件事

这将产生一个绘图like


Tags: np绘制事件pltaxprompthist平均值
1条回答
网友
1楼 · 发布于 2024-05-15 22:48:52

pcolormesh将每个元素作为一个单元绘制在x轴上。也就是说,如果绘制8列,则该数据在x轴上的跨度为0-8。但是,您还重新定义了x轴标签,以便将0-10标记为11-21

对于errorbars,您在11-21处指定了x值,或者看起来是这样,这是数据的打印位置。但是没有标记,因为您更改了ticklabels以对应于pcolormesh

这种差异就是两个图不对齐的原因。相反,您可以为errorbar使用“默认”x值,或者为pcolormesh定义x值。例如,使用:

ax.errorbar(range(11), means[0:11], yerr=uncertainties[0:11])

相关问题 更多 >