Python在绘制y轴方向的置信区间seaborn可以非常容易实现,当然也可以用Matplotlib的fill_between实现,但稍显复杂。而当绘制如下图所示的x轴方向的置信区间,Seaborn却没找到对应的函数,还是需要借助Matplotlib的fill_betweenx来实现,现将实现过程记录在此分享给更多有需要的同学。
本例所用的数据来自Seaborn库自带的数据集fmri。
置信区间的计算公式如下:
# -*- encoding: utf-8 -*-
'''
@File : FILL_BETWEENX.PY
@Time : 2022/06/16 15:01:22
@Author : HMX
@Version : 1.0
@Contact : kzdhb8023@163.com
'''
# here put the import lib
import matplotlib.pyplot as plt
import matplotlib as mpl
import seaborn as sns
import numpy as np
def cm2inch(x,y):
return (x/2.54,y/2.54)
size1 = 10.5
fontdict = {'weight': 'bold','size':size1,'family':'SimHei'}
mpl.rcParams.update(
{
'text.usetex': False,
'font.family': 'stixgeneral',
'mathtext.fontset': 'stix',
"font.family":'serif',
"font.size": size1,
"mathtext.fontset":'stix',
"font.serif": ['Times New Roman'],
}
)
df = sns.load_dataset("fmri")
# seaborn绘制x轴方向的置信区间
fig,[ax1,ax2] = plt.subplots(1,2,figsize=cm2inch(16,8))
sns.lineplot(df.timepoint,df.signal,ax = ax1)
ax1.set_title('seaborn lineplot')
# matplotlib fill_betweenx绘制
# 首先计算均值和95%置信区间
low_CIs, high_CIs, mus = [], [], []
for i in np.sort(df.timepoint.unique()):
print(i)
ds = df[df.timepoint==i]
y = ds.signal.values
mu = np.mean(y)
mus.append(mu)
sd = np.std(y)
n = len(ds)
low_CI, high_CI = mu-1.96*sd/np.sqrt(n),mu+1.96*sd/np.sqrt(n)
low_CIs.append(low_CI)
high_CIs.append(high_CI)
data = np.sort(df.timepoint.unique())
ax2.plot(mus,data)
ax2.fill_betweenx(data,low_CIs,high_CIs, alpha=0.2,label = '95%置信区间')
ax2.set_xlabel('signal')
ax2.set_ylabel('timepoint')
plt.legend(prop = fontdict)
ax2.set_title('matplotlib fill_betweenx')
plt.tight_layout()
plt.savefig(r'.fill_between_x.png',dpi = 600)
plt.show()
03 结果如下:
如果对你有帮助的话,请‘点赞’、‘收藏’,‘关注’,你们的支持是我更新的动力。
欢迎关注公众号【森气笔记】。



