如何使用具有单个分类(3 级)自变量的 statsmodels 绘制回归结果?
How to plot regression results using statsmodels with single categorical (3 levels) independent variable?
我有一个数值因变量 Y 和一个分类自变量 X,具有 3 个水平(x1、x2 和 x3)。
Y对应一个传感器的测量,X对应三个测量条件。假设我在 3 种不同条件下测量了 (Y) 的亮度 (X:x1、x2 和 x3)。
我正在使用 statsmodels python 库执行回归(测量条件如何影响亮度)
res = smf.ols(formula='Y ~ C(X)', data=df_cont).fit()
现在我需要在同一个图上绘制回归结果(线性拟合)和“原始”数据。我想到的情节类似于这个模拟示例:
[
我已经尝试了统计模型 plot_fit
和 albine_plot
但未能成功。我已经尝试关注,但我还是做不到。
非常欢迎任何有关如何实现此目的的想法!
当你像你那样拟合线性模型时,你是在估计每个类别的平均值,它不是斜率和截距拟合所有数据点,例如:
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
我有一个数值因变量 Y 和一个分类自变量 X,具有 3 个水平(x1、x2 和 x3)。
Y对应一个传感器的测量,X对应三个测量条件。假设我在 3 种不同条件下测量了 (Y) 的亮度 (X:x1、x2 和 x3)。
我正在使用 statsmodels python 库执行回归(测量条件如何影响亮度)
res = smf.ols(formula='Y ~ C(X)', data=df_cont).fit()
现在我需要在同一个图上绘制回归结果(线性拟合)和“原始”数据。我想到的情节类似于这个模拟示例:
[
我已经尝试了统计模型 plot_fit
和 albine_plot
但未能成功。我已经尝试关注
非常欢迎任何有关如何实现此目的的想法!
当你像你那样拟合线性模型时,你是在估计每个类别的平均值,它不是斜率和截距拟合所有数据点,例如:
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