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

Sva*_*rto 3 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")
Run Code Online (Sandbox Code Playgroud)

其中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()
Run Code Online (Sandbox Code Playgroud)

当前的散点图如下所示:
在此处输入图片说明

谁能帮我这个?

--尝试 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()
Run Code Online (Sandbox Code Playgroud)

导致相同的图形但没有线: 在此处输入图片说明

Tre*_*ney 20

示例数据和导入

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

# create a dataframe with sample x and y
np.random.seed(365)
x = 5*np.random.random(200)
df = pd.DataFrame({'x': x, 'y': 10*x+10*np.random.random(200)})

# add custom line to the dataframe
base_beta = [10, 5]
df['y_line'] = base_beta[0] + base_beta[1]*df.x

display(df.head())
          x          y     y_line
0  4.707279  50.634968  33.536394
1  3.208014  33.890507  26.040068
2  3.423052  37.853276  27.115262
3  2.942810  29.899257  24.714052
4  2.719436  36.932170  23.597180
Run Code Online (Sandbox Code Playgroud)

将自定义线添加到散点图

sns.relplot.map.map_dataframe

ax = sns.relplot(kind='scatter', x='x', y='y', data=df, height=3.5, aspect=1.5)
ax.map_dataframe(sns.lineplot, 'x', 'y_line', color='g')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

sns.scatterplotsns.lineplot

  • 将两个轴级图绘制到同一个图上。
fig, ax = plt.subplots(figsize=(6, 4))
p1 = sns.scatterplot(data=df, x='x', y='y', ax=ax)
p2 = sns.lineplot(data=df, x='x', y='y_line', color='g', ax=ax)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


散点图的回归线

sns.lmplot

g = sns.lmplot(data=df, x='x', y='y', line_kws={'color': 'g'}, height=3.5, aspect=1.5)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

sns.regplot

ax = sns.regplot(data=df, x='x', y='y', line_kws={'color': 'g'})
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Rob*_*bie 10

您只需调用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()
Run Code Online (Sandbox Code Playgroud)

产生:

在此处输入图片说明