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