【问题标题】:Regression line using Relplot in seaborn在 seaborn 中使用 Relplot 回归线
【发布时间】:2020-09-22 06:42:18
【问题描述】:

下面是一个我需要绘制回归线的工作示例。我在网上搜索过,但我看到了另一个函数,比如 regplot,impllot 来绘制回归线,但这里我使用的是 replot。如何使用 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()

【问题讨论】:

    标签: python python-3.x matplotlib regression seaborn


    【解决方案1】:

    您可以使用 np.polyfit(..,deg=1) 来拟合您的 y 和 x 并将其添加到 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)])
    

    【讨论】:

      猜你喜欢
      • 2021-01-09
      • 2017-09-05
      • 1970-01-01
      • 1970-01-01
      • 2021-02-17
      • 2018-03-11
      • 1970-01-01
      • 2019-06-20
      • 1970-01-01
      相关资源
      最近更新 更多