seaborn residuals/Joint 图中可能存在错误?

Possible bug in seaborn residuals/Joint plots?

我尝试了以下两个选项来绘制回归模型的残差:

ax = sns.jointplot(data=df,x="PS",y='residuals',ax=True,kind='resid',marginal_ticks=True,lowess=True)
ax = sns.jointplot(data=df,x="PS",y='residuals',ax=True,kind='reg',marginal_ticks=True,lowess=True)

sns.residplot 给出与设置了 kind='resid' 选项的 jointplot 相同的输出。

然而,它们各自给出不同的 lowess 输出,看起来残差在使用 kind=resid 时在 y=0 处围绕 y 轴旋转。两种情况都使用了相同的数据。

两个图中都绘制了残差,但 kind='resid' 的残差是错误的。这可能是 resid 代码中的错误吗?即使应用了标准化过程,残差也不应从负值变为正值。

底层轴级函数是sns.regplotsns.residplot。问题 post 中使用的示例数据似乎使用了接近零附近正态分布的 y 值,这使得很难看出发生了什么。

下面的代码使用 penguins 数据集的 Gentoo 物种。

左边的regplot为原始数据带回归线。 y值均为正,回归线斜率向上。

右边的residplot是减去回归线后的数据。当原始数据高于回归线时,y 值为正,低于回归线时为负。 residplot 有助于评估回归(在本例中为线性)是否合适。

链接的tutorial post和视频可能有助于更好地理解残差图。

import matplotlib.pyplot as plt
import seaborn as sns

penguins = sns.load_dataset('penguins')
penguins = penguins[penguins['species'] == 'Gentoo']
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(14, 4), sharex=True)
sns.regplot(data=penguins, x="bill_length_mm", y="bill_depth_mm", ax=ax1)
ax1.set_title("regplot")
sns.residplot(data=penguins, x="bill_length_mm", y="bill_depth_mm", ax=ax2)
ax2.set_title("residplot")

plt.tight_layout()
plt.show()

如果您的输入数据已经是残差,则两个图看起来非常相似:

import seaborn as sns
import matplotlib.pyplot as plt
from scipy import stats

penguins = sns.load_dataset('penguins').dropna()
penguins = penguins[penguins['species'] == 'Gentoo']
x = penguins['bill_length_mm']
y = penguins['bill_depth_mm']
regr = stats.linregress(x, y)
y -= regr.slope * x + regr.intercept  # calculate the residuals

fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(15, 4))
sns.regplot(x=x, y=y, lowess=True, ax=ax1)
ax1.set_title('regplot')
sns.residplot(x=x, y=y, lowess=True, ax=ax2)
ax2.set_title('residplot')

plt.tight_layout()
plt.show()