2015-10-10 206 views
10

繪製2個distplots或散點圖中的次要情節的偉大工程:如何繪製2個seaborn lmplots並排?

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() 

Subplot example

但是,當我做相同的lmplot代替或者其他類型的圖表,我得到一個錯誤:

AttributeError: 'AxesSubplot' object has no attribute 'lmplot'

是否有任何方法可以並排繪製這些圖表類型?

+0

BTW:你的例子不運行。變量'x'沒有在數據框的''y''列的定義中定義。 –

+0

感謝您注意@PaulH。糾正。 – samthebrand

回答

24

你得到這個錯誤是因爲matplotlib及其對象完全不瞭解seaborn函數。

通過你的軸對象(即ax1ax2),以seaborn.regplot或者你可以跳過定義的,並使用col kwarg的seaborn.lmplot

與您相同的進口,預定義你的斧頭和使用regplot看起來是這樣的:

# 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) 

enter image description here

使用lmplot需要您dataframe to be tidy。從上面的代碼繼續:

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) 

enter image description here