在散点图上叠加线函数 - seaborn

时间:2017-10-06 04:37:28

标签: python matplotlib seaborn

我的挑战是在我已有的散点图上叠加自定义线函数图,代码如下所示:

base_beta = results.params
X_plot = np.linspace(0,1,400)

g = sns.FacetGrid(data, size = 6)
g = g.map(plt.scatter, "usable_area", "price", edgecolor="w")

base_beta只是一个常数,然后是一个系数。基本上,我想覆盖一个绘制线y = constant + coefficient * x

的函数

我尝试使用此方法覆盖一行,但它不起作用。

g = g.map_dataframe(plt.plot, X_plot, X_plot*base_beta[1]+base_beta[0], 'r-')
plt.show()

当前的散点图如下:
enter image description here

任何人都能帮助我吗?

- ATTEMPT 1

base_beta = results.params
X_plot = np.linspace(0,1,400)
Y_plot = base_beta [0] + base_beta[1]*X_plot

g = sns.FacetGrid(data, size = 6)
g = g.map(plt.scatter, "usable_area", "price", edgecolor="w")
plt.plot(X_plot, Y_plot, color='r')
plt.show()

导致同一图表但没有行: enter image description here

2 个答案:

答案 0 :(得分:3)

您只需致电plt.plot即可在数据上划一条线。

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

data = pd.DataFrame()
data['usable_area'] = 5*np.random.random(200)
data['price'] =  10*data['usable_area']+10*np.random.random(200)

X_plot = np.linspace(0, 7, 100)
Y_plot = 10*X_plot+5

g = sns.FacetGrid(data, size = 6)
g = g.map(plt.scatter, "usable_area", "price", edgecolor="w")
plt.plot(X_plot, Y_plot, color='r')
plt.show()

产地:

enter image description here

答案 1 :(得分:0)

您也可以在数据上覆盖一个Seaborn绘图,只要有构成该线的点即可(以下,我将它们称为x_predy_pred):

fig, ax = plt.subplots(figsize=(11, 8.5))
sns.scatterplot(x='M2NS_PC1', y='FII5', data=ir_ms, ax=ax)
ax.axhline(y=0, color='k', linewidth=1)  # added because i want the origin
ax.axvline(x=0, color='k', linewidth=1)

fitted = sm.ols(formula='FII5 ~ M2NS_PC1', data=ir_ms).fit(cov_type='HC3')

x = ir_ms['M2NS_PC1']
x_pred = np.linspace(x.min() - 1, x.max() + 1, 50)
y_pred = fitted.predict(exog=dict(M2NS_PC1=x_pred))

sns.lineplot(x=x_pred, y=y_pred, ax=ax)

然后,将它们全部绘制在同一轴上。

enter image description here