【问题标题】:How to plot statsmodels linear regression (OLS) cleanly如何干净地绘制 statsmodels 线性回归 (OLS)
【发布时间】:2017-07-04 20:34:45
【问题描述】:

问题陈述:

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

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

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

Statsmodels 有一个 variety of methods for plotting regression (a few more details about them here) 但它们似乎都不是超级简单的“只需在数据之上绘制回归线”——plot_fit 似乎是最接近的东西。

问题:

  • 上面的第一张图片来自pandas的plot函数,它返回一个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

abline_plot

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

【问题讨论】:

  • 请发布一个示例数据集(看起来你的数据集很小,所以你可以发布整个内容)。一般来说,我会推荐seaborn.regplot,如果你可以接受这种依赖,它会满足你的需求。
  • @IgorRaush 见上文

标签: pandas matplotlib statsmodels


【解决方案1】:

正如我在 cmets 中提到的,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)

【讨论】:

  • 感谢@IgorRaush!我想我会坚持第二种解决方案。尽管 seaborn 看起来像一个优秀的库,但我想保持低依赖的数量,而且由于我只制作一种情节并且已经依赖于 pandas 和 statsmodels,我会坚持那些可以为我做的事情.但我希望其他人受到启发使用 seaborn!
  • 只是多逛了一下,在statsmodels 中找到了abline_plot。请查看编辑。
  • 由于某种原因,它仅在与散点图结合使用时才对我有用。我猜它自己没有正确设置轴限制。
  • 结合是什么意思?请问你更新你上次的代码sn-p吗?
  • 查看我最近的编辑(ax=ax in abline_plot)。 abline_plot 似乎没有正确设置轴限制。但是,如果您将 motif.plot(...) 返回的轴传递给它,则这些轴已经设置了正确的限制。
猜你喜欢
  • 1970-01-01
  • 2014-03-30
  • 2015-12-31
  • 2021-03-18
  • 1970-01-01
  • 2015-05-09
  • 2014-02-20
  • 2016-12-29
  • 1970-01-01
相关资源
最近更新 更多