1、问题的来源:
我用getdist包得到的corner图,它的best fit 以及1σ区间有的时候是2位小数,有的时候是3位小数(如下图1)。导师觉得这样的结果不美观,让我统一改成2位小数。于是就有这次漫长的搜集资料,调代码的过程。
图1 best fit 以及1σ区间有2位小数,有3位小数。
2、增加功能,修改代码过程
只能说网上相关的资料太少了,再次印证了我们研究的小众。幸运的是,Change number of decimals on a triplot with matplotlib on only one tick of a subplot 这篇文章一个回答给了我灵感,我可以将getdist生成的图看成matplotlib生成的图,修改它相关的表头等等。
2.1、getdist的api (getdist.plots - GetDist 1.4.6 documentation)
getdist的api给了很多设置corner图的属性列表,我们可以通过修改这些属性的值来得到我们想要图的效果,其中为了显示best fit 以及1σ区间,我们将title_limit=1,如果想要2σ区间,我们只需要将title_limit设置为2。可是并没有设置保留小数点位数的属性,为此我进行了下面的代码补充。
图2 getdist的api
2.2、新增代码部分
\Omega_m = 0.288^{+0.060}_{-0.20}
对于如上的表头,两部分需要保留2位,0.288与+0.060,值得注意的是,后面的1σ区间还要保留+号,所以我的匹配函数写了两个分别对它们进行匹配。
import re
panttern=r"([-+]?\d*\.\d+|[-+]?\d+)"
def format_match(x):
if '+' in x.group(0) or '-' in x.group(0):
return f"{x.group(0)[0]}{float(x.group(0)[1:]):.2f}"
else:
return f"{float(x.group(0)):.2f}"
for ax in g.fig.axes:
title=ax.get_title()
print(title)
# #提取标题中的数字部分
# numbers=[float(s) if s.replace('.','',1).isdigit() else s for s in title.split()]
# #格式化数字部分为两位小数
# formatted_numbers=[f'{num:.2f}' if isinstance(num,float) else num for num in numbers]
fomatted_title=re.sub(panttern,lambda x: format_match(x),title)
ax.set_title(fomatted_title)
上述代码完整copy到你的代码,就可以限制其结果位数啦。