2015-10-10 14 views
10

サブプロットに2 distplotsや散布図をプロットすることは素晴らしい作品:海底の2枚のプロットを並べてプロットするにはどうすればいいですか?

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

:上記のコードに引き続き、あなたの例では、実行されません。変数 'x'はデータフレームの' 'y''カラムの定義で定義されていません。 –

+0

@PaulHに気付いてありがとう。修正されました。 – samthebrand

答えて

24

matplotlibとそのオブジェクトは海水機能を完全に認識していないため、このエラーが発生します。

seaborn.regplotにあなたのAxesオブジェクト(すなわち、ax1ax2)を渡したり、それらを定義スキップして同じ輸入してseaborn.lmplot

col kwargを使用することができ、自分の軸を事前に定義し、regplotを使用すると、このようになります:lmplotを使用して

# 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

あなたが必要です。

ところで
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

関連する問題