如何在散点图中可视化非线性关系

tob*_*bip 5 python matplotlib statsmodels

我想直观地探索两个变量之间的关系.在如下的密集散点图中,这种关系的功能形式是不可见的:

散点图

如何在Python中的散点图中添加lowess smooth?

或者您有任何其他建议来直观地探索非线性关系吗?

我尝试了以下但是它没有正常工作(借鉴Michiel de Hoon的一个例子):

import numpy as np
from statsmodels.nonparametric.smoothers_lowess import lowess
x = np.arange(0,10,0.01)
ytrue = np.exp(-x/5.0) + 2*np.sin(x/3.0)

# add random errors with a normal distribution                      
y = ytrue + np.random.normal(size=len(x))
plt.scatter(x,y,color='cyan')

# calculate a smooth curve through the scatter plot
ys = lowess(x, y)
_ = plt.plot(x,ys,'red',linewidth=1)

# draw the true values for comparison
plt.plot(x,ytrue,'green',linewidth=3)
Run Code Online (Sandbox Code Playgroud)

LOWESS

低沉的平滑(红线)很奇怪.

编辑:

以下矩阵还包括lowess平滑器(取自CV上的此问题): 在此输入图像描述

有人有这样的图表的代码吗?

mwa*_*kom 20

你也可以用seaborn:

import numpy as np
import seaborn as sns

x = np.arange(0, 10, 0.01)
ytrue = np.exp(-x / 5) + 2 * np.sin(x / 3)
y = ytrue + np.random.normal(size=len(x))

sns.regplot(x, y, lowess=True)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


DSM*_*DSM 9

lowess文档:

Definition: lowess(endog, exog, frac=0.6666666666666666, it=3, delta=0.0, is_sorted=False, missing='drop', return_sorted=True)

[...]

Parameters
----------
endog: 1-D numpy array
    The y-values of the observed points
exog: 1-D numpy array
    The x-values of the observed points
Run Code Online (Sandbox Code Playgroud)

它接受其他顺序的参数.它不仅返回y:

>>> lowess(y, x)
array([[  0.00000000e+00,   1.13752478e+00],
       [  1.00000000e-02,   1.14087128e+00],
       [  2.00000000e-02,   1.14421582e+00],
       ..., 
       [  9.97000000e+00,  -5.17702654e-04],
       [  9.98000000e+00,  -5.94304755e-03],
       [  9.99000000e+00,  -1.13692896e-02]])
Run Code Online (Sandbox Code Playgroud)

但如果你打电话

ys = lowess(y, x)[:,1]
Run Code Online (Sandbox Code Playgroud)

你应该看到类似的东西

示例低位输出