【问题标题】:How to plot regression results using statsmodels with single categorical (3 levels) independent variable?如何使用具有单分类(3 级)自变量的 statsmodels 绘制回归结果?
【发布时间】:2023-03-15 12:03:02
【问题描述】:

我有一个数值因变量 Y 和一个分类自变量 X,有 3 个级别(x1、x2 和 x3)。

Y对应一个传感器的测量,X对应三个测量条件。假设我在 3 种不同条件(X:x1、x2 和 x3)下测量了 (Y) 的亮度。

我正在使用 statsmodels python 库执行回归(测量条件如何影响亮度)

res = smf.ols(formula='Y ~ C(X)', data=df_cont).fit()

现在我需要在同一个图上绘制回归结果(线性拟合)和“原始”数据。我想到的情节类似于这个模拟示例:

[

我已经尝试了plot_fitalbine_plot 的statsmodels,但没有成功。我已经尝试关注this question,但我仍然无法做到。

非常欢迎任何关于如何实现这一点的想法!

【问题讨论】:

    标签: python matplotlib plot statistics statsmodels


    【解决方案1】:

    当您像以前那样拟合线性模型时,您正在估计每个类别的平均值,它不是斜率和截距拟合所有数据点,例如:

    import pandas as pd
    import matplotlib.pyplot as plt
    import seaborn as sns
    import statsmodels.api as sm
    import numpy as np
    import statsmodels.formula.api as smf
    
    df = pd.DataFrame({'Y':np.random.normal(np.repeat([0,1.5,2.5],20),1,60),
                      'X':np.repeat(['x1','x2','x3'],20)})
    
    df['X'] = pd.Categorical(df['X'],categories=['x1','x2','x3'])
    
    res = smf.ols(formula= "Y ~ X",data=df).fit()
    res.summary()
    
        coef    std err t   P>|t|   [0.025  0.975]
    Intercept   -0.0418 0.233   -0.180  0.858   -0.508  0.424
    X[T.x2] 1.3507  0.329   4.102   0.000   0.691   2.010
    X[T.x3] 2.5947  0.329   7.880   0.000   1.935   3.254
    

    要绘制这些结果,您可以:

    fig, ax = plt.subplots()
    sns.scatterplot(data=df,x = "X",y = "Y",ax=ax)
    ncat = len(res.params)
    ax.scatter(x = np.arange(ncat)+0.1,y = res.params , color = "#FE9898")
    ax.vlines(x = np.arange(ncat)+0.1,
              ymin = res.conf_int().iloc[:,0],
              ymax = res.conf_int().iloc[:,1],
             color = "#FE9898")
    

    如果你真的必须强制一条线,请记住这不是来自你刚刚展示的回归:

    sns.regplot(x = df['X'].cat.codes,y = df['Y'],ax=ax,scatter=False,color="#628395")
    fig
    

    【讨论】:

      猜你喜欢
      • 2021-12-20
      • 1970-01-01
      • 2020-01-25
      • 1970-01-01
      • 2016-05-13
      • 2020-01-10
      • 2018-06-12
      • 2018-02-06
      • 2014-12-22
      相关资源
      最近更新 更多