【问题标题】:Python 2d Ratio Plot with weighted mean trendline带有加权平均趋势线的 Python 2d 比率图
【发布时间】: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


【解决方案1】:

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

对于您的误差线,您将 x 值指定为 11-21,或者看起来是这样,这是绘制数据的位置。但是由于您将刻度标签更改为与 pcolormesh 相对应,因此未标记。

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

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

【讨论】:

  • 感谢您的帮助
猜你喜欢
  • 2019-03-19
  • 2021-12-11
  • 2021-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-15
相关资源
最近更新 更多