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

Ale*_*ail 15 matplotlib pandas statsmodels

问题陈述:

我在pandas数据帧中有一些不错的数据.我想对它进行简单的线性回归:

在此输入图像描述

使用statsmodels,我执行我的回归.现在,我如何得到我的情节?我尝试过statsmodels的plot_fit方法,但情节有点时髦:

在此输入图像描述

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

Statsmodels有多种绘制回归的方法(这里有一些关于它们的更多细节),但它们似乎都不是超级简单的"只是在数据上绘制回归线" - plot_fit似乎是最接近的东西.

问题:

  • 上面的第一张图片来自熊猫的情节函数,它返回一个matplotlib.axes._subplots.AxesSubplot.我可以轻松地将回归线叠加到该图上吗?
  • 在我忽略的statsmodels中是否有一个函数?
  • 有没有更好的方法来组合这个数字?

两个相关问题:

似乎都没有一个好的答案.

样本数据

按照@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
Run Code Online (Sandbox Code Playgroud)

abline_plot

我试过这个,但它似乎不起作用......不确定原因:

在此输入图像描述

Igo*_*ush 20

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

import seaborn as sns

sns.regplot(x='motifScore', y='expression', data=motif)
Run Code Online (Sandbox Code Playgroud)

sns.regplot


或者,您可以使用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])
Run Code Online (Sandbox Code Playgroud)

手册


另一种解决方案是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)
Run Code Online (Sandbox Code Playgroud)

abline_plot