我正在尝试在线性回归图上绘制残差。它起作用,只有一个警告。残差和数据点之间存在令人不愉快的重叠。有没有办法告诉matplotlib先绘制残差,然后再绘制Seaborn图。我尝试更改代码顺序,但没有帮助。
import numpy as np
import pandas as pd
import seaborn as sns
from pylab import *
from sklearn.linear_model import LinearRegression
x = np.array([1, 2, 3, 4, 5, 7, 8, 9, 10])
y = np.array([-3, 0, 4, 5, 9, 5, 7, 7, 12])
dat = pd.DataFrame({'x': x, 'y': y})
x = x.reshape(-1,1)
y = y.reshape(-1,1)
linear_model = LinearRegression()
linear_model.fit(X=x, y=y)
pred = linear_model.predict(x)
for ix in range(len(x)):
plot([x[ix], x[ix]], [pred[ix], y[ix]], '#C9B97D')
g = sns.regplot(x='x', y='y', data=dat, ci=None, fit_reg=True)
sns.set(font_scale=1.1)
g.figure.set_size_inches(6, 6)
sns.set_style('ticks')
sns.despine()
答案 0 :(得分:2)
您要查找的参数是zorder
。这样,您可以控制哪个对象显示在图形的顶部。
对于regplot
,您必须使用参数scatter_kws
,该参数是要传递给内部使用的plt.scatter
的参数字典。
您的sns.regplot
变为:
g = sns.regplot(x='x', y='y', data=dat, ci=None, fit_reg=True,
scatter_kws={"zorder":10, "alpha":1})
请注意,我已将alpha
设置为1,以使标记不透明