如何干净地绘制 statsmodels 线性回归 (OLS)

How to plot statsmodels linear regression (OLS) cleanly

问题陈述:

我在 pandas 数据框中有一些不错的数据。我想运行对其进行简单线性回归:

我使用统计模型执行回归。现在,我如何获得我的情节?我试过 statsmodels 的 plot_fit 方法,但情节有点古怪:

我希望得到一条代表回归实际结果的水平线。

Statsmodels 有一个 variety of methods for plotting regression (a few more details about them here) 但其中 none 似乎是超级简单的 "just plot the regression line on top of your data" -- plot_fit 似乎是最接近的东西。

问题:

两个相关问题:

似乎都没有很好的答案。

示例数据

根据@IgorRaush 的要求

        motifScore  expression
6870    1.401123    0.55
10456   1.188554    -1.58
12455   1.476361    -1.75
18052   1.805736    0.13
19725   1.110953    2.30
30401   1.744645    -0.49
30716   1.098253    -1.59
30771   1.098253    -2.04

abline_plot

我试过这个,但它似乎不起作用...不知道为什么:

正如我在评论中提到的,seaborn 是统计数据可视化的绝佳选择。

import seaborn as sns

sns.regplot(x='motifScore', y='expression', data=motif)


或者,您可以使用 statsmodels.regression.linear_model.OLS 并手动绘制回归线。

import statsmodels.api as sm

# regress "expression" onto "motifScore" (plus an intercept)
model = sm.OLS(motif.expression, sm.add_constant(motif.motifScore))
p = model.fit().params

# generate x-values for your regression line (two is sufficient)
x = np.arange(1, 3)

# scatter-plot data
ax = motif.plot(x='motifScore', y='expression', kind='scatter')

# plot regression line on the same axes, set x-axis limits
ax.plot(x, p.const + p.motifScore * x)
ax.set_xlim([1, 2])


另一种解决方案是 statsmodels.graphics.regressionplots.abline_plot,它去除了上述方法中的一些样板文件。

import statsmodels.api as sm
from statsmodels.graphics.regressionplots import abline_plot

# regress "expression" onto "motifScore" (plus an intercept)
model = sm.OLS(motif.expression, sm.add_constant(motif.motifScore))

# scatter-plot data
ax = motif.plot(x='motifScore', y='expression', kind='scatter')

# plot regression line
abline_plot(model_results=model.fit(), ax=ax)