【Python基础绘图】Matplotlib fill_betweenx绘制x轴方向的置信区间

本文介绍了如何利用Python的Matplotlib库中的fill_betweenx函数绘制x轴方向的置信区间,作为Seaborn库的补充。通过示例展示了从Seaborn的fmri数据集中获取数据,计算置信区间,并使用matplotlib进行可视化的过程。最终生成了x轴置信区间的图表,为数据展示提供了新的视角。
摘要由CSDN通过智能技术生成

Matplotlib fill_betweenx绘制x轴方向的置信区间

在这里插入图片描述

01 引言:

Python在绘制y轴方向的置信区间seaborn可以非常容易实现,当然也可以用Matplotlib的fill_between实现,但稍显复杂。而当绘制如下图所示的x轴方向的置信区间,Seaborn却没找到对应的函数,还是需要借助Matplotlib的fill_betweenx来实现,现将实现过程记录在此分享给更多有需要的同学。
在这里插入图片描述

02 代码如下:

本例所用的数据来自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 结果如下:

在这里插入图片描述

​如果对你有帮助的话,请‘点赞’、‘收藏’,‘关注’,你们的支持是我更新的动力。
欢迎关注公众号【森气笔记】。

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值