本文介绍了如何并排绘制2个seaborn lmplots?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在子图中绘制2个distplots或散点图效果很好:

 将matplotlib.pyplot导入为plt 
import numpy as np
导入seaborn为sns
导入pandas为pd
%matplotlib内联

#create df
x = np.linspace(0,2 * np .pi,400)
df = pd.DataFrame({'x':x,'y':np.sin(x ** 2)})

#两个子图
f,(ax1,ax2)= plt.subplots(1,2,sharey = True)
ax1.plot(df.x,df.y)
ax1.set_title('分享Y轴' )
ax2.scatter(df.x,df.y)

plt.show()


但是当我使用 lmplot执行相同操作时

code>而不是其他任何一种类型的图表我都收到错误:

是有没有办法并排绘制这些图表类型?

解决方案

您收到该错误,因为matplotlib及其对象完全没有意识到seaborn函数。



传递你的轴对象(即 ax1 ax2



使用lmplot需要你的


Plotting 2 distplots or scatterplots in a subplot works great:

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

# create df
x = np.linspace(0, 2 * np.pi, 400)
df = pd.DataFrame({'x': x, 'y': np.sin(x ** 2)})

# Two subplots
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.plot(df.x, df.y)
ax1.set_title('Sharing Y axis')
ax2.scatter(df.x, df.y)

plt.show()

But when I do the same with an lmplot instead of either of the other types of charts I get an error:

Is there any way to plot these chart types side by side?

解决方案

You get that error because matplotlib and its objects are completely unaware of seaborn functions.

Pass your axes objects (i.e., ax1 and ax2) to seaborn.regplot or you can skip defining those and use the col kwarg of seaborn.lmplot

With your same imports, pre-defining your axes and using regplot looks like this:

# create df
x = np.linspace(0, 2 * np.pi, 400)
df = pd.DataFrame({'x': x, 'y': np.sin(x ** 2)})
df.index.names = ['obs']
df.columns.names = ['vars']

idx = np.array(df.index.tolist(), dtype='float')  # make an array of x-values

# call regplot on each axes
fig, (ax1, ax2) = plt.subplots(ncols=2, sharey=True)
sns.regplot(x=idx, y=df['x'], ax=ax1)
sns.regplot(x=idx, y=df['y'], ax=ax2)

Using lmplot requires your dataframe to be tidy. Continuing from the code above:

tidy = (
    df.stack() # pull the columns into row variables   
      .to_frame() # convert the resulting Series to a DataFrame
      .reset_index() # pull the resulting MultiIndex into the columns
      .rename(columns={0: 'val'}) # rename the unnamed column
)
sns.lmplot(x='obs', y='val', col='vars', hue='vars', data=tidy)

这篇关于如何并排绘制2个seaborn lmplots?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 19:06