本文介绍了在Seaborn中使用Relplot的回归线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是一个工作示例,我需要在其中绘制回归线.我已经在网上搜索过,但我看到了另一个函数,如 regplot、implot 来绘制回归线,但在这里我使用的是 replot.如何使用relplot绘制回归线?
Below is a working example where I need to draw regression line. I have searched online but I see another function like regplot, implot to draw regression lines but here I am using replot. How I can draw regression line using relplot?
from matplotlib import pyplot as plt
import pandas as pd
import seaborn as sns
d = {'x-axis':[100,915,298,299], 'y-axis': [1515,1450,1313,1315],
'text':['point1','point2','point3','point4']}
df = pd.DataFrame(d)
p1 = sns.relplot(x='x-axis', y='y-axis',data=df )
ax = p1.axes[0,0]
for idx,row in df.iterrows():
x = row[0]
y = row[1]
text = row[2]
ax.text(x+.05,y,text, horizontalalignment='left')
p1.set(xticks=[i for i in range(0, max(df['x-axis']) + 50, 50)],
yticks=[i for i in range(0, max(df['y-axis']) + 500, 500)])
plt.show()
推荐答案
您可以使用np.polyfit(..,deg = 1)来拟合y和x并将其添加到relplot中:
You can use np.polyfit(..,deg=1) to fit your y and x and add it onto relplot:
from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
import seaborn as sns
b, a = np.polyfit(df['x-axis'], df['y-axis'], 1)
xtest = np.linspace(df['x-axis'].min(),df['x-axis'].max(),10)
p1 = sns.relplot(x='x-axis', y='y-axis',data=df,height=3,aspect=2.5)
ax = p1.axes[0,0]
ax.plot(xtest, a + b* xtest, '-')
for idx,row in df.iterrows():
ax.text(row[0]+.05,row[1],row[2], horizontalalignment='left')
p1.set(xticks=[i for i in range(0, max(df['x-axis']) + 50, 50)],
yticks=[i for i in range(0, max(df['y-axis']) + 500, 500)])
或者您可以使用 sns.regplot()
:
fig,ax = plt.subplots(figsize=(8,4))
sns.regplot(x='x-axis', y='y-axis',data=df,ci=False,ax=ax)
for idx,row in df.iterrows():
ax.text(row[0]+.05,row[1],row[2], horizontalalignment='left')
ax.set(xticks=[i for i in range(0, max(df['x-axis']) + 50, 50)],
yticks=[i for i in range(0, max(df['y-axis']) + 500, 500)])
这篇关于在Seaborn中使用Relplot的回归线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!