【Pyhton基础绘图】Seaborn绘制具有拟合置信区间的散点图

【Pyhton基础绘图】Seaborn绘制具有拟合置信区间的散点图

绘制散点图时,想绘制如下图所示的带有拟合置信区间的拟合线,该如何实现?其实借助seaborn可以轻松实现。

效果如下:

在这里插入图片描述

代码如下:

# -*- encoding: utf-8 -*-
'''
@File    :   lineregression_demo.py
@Time    :   2022/06/02 22:12:19
@Author  :   HMX 
@Version :   1.0
@Contact :   kdhb8023@163.com
'''# here put the import lib
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import seaborn as sns
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
​
​
# 构造数据
np.random.seed(1234)
x = np.random.randint(10,90,(100,1))
y = [2*i+(np.random.randint(-9,9))**2+np.random.randint(200) for i in x]
# 绘制散点图
​
size1 = 20
fontdict = {'weight': 'bold','size':size1,'color':'k','family':'SimHei'}
mpl.rcParams.update(
    {
    'text.usetex': False,
    'font.family': 'stixgeneral',
    'mathtext.fontset': 'stix',
    "font.family":'serif',
    "font.size": size1,
    "font.serif": ['Times New Roman'],
    }
    )
fig,ax = plt.subplots(figsize = (8,6))
sns.regplot(x,y,ax = ax)
ax.set_xlim(0,100)
ax.set_ylim(0,400)
ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')# 拟合方程
model = LinearRegression()
model.fit(x,y)
a = model.coef_[0][0]
b = model.intercept_[0]
ax.text(8,350,'$y$ = {:.2f}$x$ + {:.2f}'.format(a,b))# R2
r2 = r2_score(y,model.predict(x)).round(2)
ax.text(8,300,f'$R$$^{2}$ = {r2}')
plt.tight_layout()
plt.savefig('out.png',dpi = 600)
plt.show()

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值