在同一个海啸地块上绘制多个线性回归

时间:2016-03-16 03:12:32

标签: python matplotlib plot seaborn

假设我有以下内容:

x1 = np.random.randn(50)
y1 = np.random.randn(50) * 100
x2 = np.random.randn(50)
y2 = np.random.randn(50) * 100

df1 = pd.DataFrame({'x1':x1, 'y1': y1})
df2 = pd.DataFrame({'x2':x2, 'y2': y2})

sns.lmplot('x1', 'y1', df1, fit_reg=True, ci = None)
sns.lmplot('x2', 'y2', df2, fit_reg=True, ci = None)

这将创建2个单独的图。如何将df2中的数据添加到SAME图表中?我在网上找到的所有seaborn示例似乎都集中在如何创建相邻图表(例如,通过' hue'和#39; col_wrap'选项)。此外,我不想使用其他列可能存在的数据集示例,因为这在我正在处理的项目中没有自然含义。

如果有matplotlib / seaborn功能的混合物是实现这一目标所必需的,我将不胜感激,如果有人可以帮助说明。谢谢!

2 个答案:

答案 0 :(得分:5)

您可以使用seaborn' FacetGrid课程来获得所需的结果。 您需要使用以下行替换您的绘图调用:

# sns.lmplot('x1', 'y1', df1, fit_reg=True, ci = None)
# sns.lmplot('x2', 'y2', df2, fit_reg=True, ci = None)
df = pd.concat([df1.rename(columns={'x1':'x','y1':'y'})
                .join(pd.Series(['df1']*len(df1), name='df')), 
                df2.rename(columns={'x2':'x','y2':'y'})
                .join(pd.Series(['df2']*len(df2), name='df'))],
               ignore_index=True)

pal = dict(df1="red", df2="blue")
g = sns.FacetGrid(df, hue='df', palette=pal, size=5);
g.map(plt.scatter, "x", "y", s=50, alpha=.7, linewidth=.5, edgecolor="white")
g.map(sns.regplot, "x", "y", ci=None, robust=1)
g.add_legend();

这将产生这个情节:

enter image description here

如果我理解正确,那就是你需要的。

请注意,您需要注意.regplot参数,并且可能希望更改我放置的值作为示例。

答案 1 :(得分:0)

选项 1:sns.regplot

  • 在这种情况下,最容易实现的解决方案是使用 sns.regplot,这是一个轴级函数,因为这不需要组合 df1df2
import pandas as pd
import seaborn
import matplotlib.pyplot as plt

# create the figure and axes
fig, ax = plt.subplots(figsize=(6, 6))

# add the plots for each dataframe
sns.regplot(x='x1', y='y1', data=df1, fit_reg=True, ci=None, ax=ax, label='df1')
sns.regplot(x='x2', y='y2', data=df2, fit_reg=True, ci=None, ax=ax, label='df2')
ax.set(ylabel='y', xlabel='x')
ax.legend()
plt.show()

enter image description here


选项 2:sns.lmplot

  • 根据sns.FacetGrid,使用图形级函数比直接使用FacetGrid更好。
  • df1df2 组合成一个长格式,然后将 sns.lmplothue 参数一起使用。
  • 使用 seaborn 时,几乎总是需要长格式的数据。
    • 习惯上使用 pandas.DataFrame.stackpandas.melt 将 DataFrame 从宽转换为长。
    • 因此,df1df2 必须重命名列,并有一个额外的标识列。这允许将它们连接到 axis=0(默认长格式),而不是 axis=1(宽格式)。
  • 有多种方法可以组合 DataFrame:
    1. 如果组合几个 DataFrame,answer 中的 Primer 中的组合方法很好。
    2. 但是,如下所示的函数更适合组合多个 DataFrame。
def fix_df(data: pd.DataFrame, name: str) -> pd.DataFrame:
    """rename columns and add a column"""
    # rename columns to a common name
    data.columns = ['x', 'y']
    # add an identifying value to use with hue
    data['df'] = name
    return data


# create a list of the dataframes
df_list = [df1, df2]

# update the dataframes by calling the function in a list comprehension
df_update_list = [fix_df(v, f'df{i}') for i, v in enumerate(df_list, 1)]

# combine the dataframes
df = pd.concat(df_update_list).reset_index(drop=True)

# plot the dataframe
sns.lmplot(data=df, x='x', y='y', hue='df', ci=None)

enter image description here

注意事项

  • 用于此答案的软件包版本:
    • pandas v1.2.4
    • seaborn v0.11.1
    • matplotlib v3.3.4
相关问题