作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
seaborn 中的 lmplot
通过截距拟合回归模型。然而,有时我想拟合回归模型无截距,即通过原点回归。
例如:
In [1]: import numpy as np
...: import pandas as pd
...: import seaborn as sns
...: import matplotlib.pyplot as plt
...: import statsmodels.formula.api as sfa
...:
In [2]: %matplotlib inline
In [3]: np.random.seed(2016)
In [4]: x = np.linspace(0, 10, 32)
In [5]: y = 0.3 * x + np.random.randn(len(x))
In [6]: df = pd.DataFrame({'x': x, 'y': y})
In [7]: r = sfa.ols('y ~ x + 0', data=df).fit()
In [8]: sns.lmplot(x='x', y='y', data=df, fit_reg=True)
Out[8]: <seaborn.axisgrid.FacetGrid at 0xac88a20>
我想要的数字:
In [9]: fig, ax = plt.subplots(figsize=(5, 5))
...: ax.scatter(x=x, y=y)
...: ax.plot(x, r.fittedvalues)
...:
Out[9]: [<matplotlib.lines.Line2D at 0x5675a20>]
最佳答案
seaborn API 不允许直接更改线性回归模型。
调用链是:
_RegressionPlotter.plot()
被调用来生成绘图_RegressionPlotter.lineplot()
执行拟合图regression
模块self.fit_fast(grid)
在你的情况下。要使用不同的回归模型,您可以:
_RegressionPlotter
类并更改 lineplot()
行为fit_regression()
或fit_fast()
回归模块中的方法要做这样的seaborn猴子补丁,可以引用an answer I made a while ago that does the same type of hack 。这太糟糕了,圣诞老人可能会不高兴。这意味着您可以根据预期目的动态修改seaborn。
当然,您需要实现自己的回归模型才能在 for y = a * x
中具有规律。而不是 y = (a * x) + b
。 importanceofbeingernest已经在评论中指出this SO question就此而言。
一种优雅的方法是构建自己的情节,但您已经在自己的问题中回答了该部分。
引用你自己的问题(我没有检查提供的代码):
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.formula.api as sfa
np.random.seed(2016)
x = np.linspace(0, 10, 32)
y = 0.3 * x + np.random.randn(len(x))
df = pd.DataFrame({'x': x, 'y': y})
r = sfa.ols('y ~ x + 0', data=df).fit()
fig, ax = plt.subplots(figsize=(5, 5))
ax.scatter(x=x, y=y)
ax.plot(x, r.fittedvalues)
关于python - 如何使用 `lmplot` 绘制无截距的线性回归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34725835/
我是一名优秀的程序员,十分优秀!