las*_*lex 5 python plot matplotlib 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)
Run Code Online (Sandbox Code Playgroud)
这将创建2个单独的图。如何将df2中的数据添加到SAME图上?我在网上找到的所有最原始的示例似乎都集中在如何创建相邻图形上(例如,通过“ hue”和“ col_wrap”选项)。另外,我不希望使用可能存在附加列的数据集示例,因为这在我正在从事的项目中没有自然的含义。
如果要实现此功能需要混合使用matplotlib / seaborn函数,那么如果有人可以帮助说明,我将不胜感激。谢谢!
您可以使用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();
Run Code Online (Sandbox Code Playgroud)
这将产生以下图:
如果我正确理解的话,这就是您所需要的。
请注意,您将需要注意.regplot参数,并且可能想要更改我作为示例输入的值。
| 归档时间: |
|
| 查看次数: |
3444 次 |
| 最近记录: |