栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

【Python基础绘图】Matplotlib fill

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Python基础绘图】Matplotlib fill

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 结果如下:

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/980428.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号