Regression line using Relplot in seaborn

老子叫甜甜 提交于 2021-02-10 20:00:35

问题


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()

回答1:


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)])

Or you can use 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)])



来源:https://stackoverflow.com/questions/62175006/regression-line-using-relplot-in-seaborn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!