<Python, seaborn> distplot に 凡例追加

distplotに凡例ラベルlegend labelを追加する方法。

In [1]: import pandas as pd

In [2]: import numpy as np

In [3]: import seaborn as sns

In [4]: import matplotlib.pyplot as plt

In [7]: df0 = pd.DataFrame(data=np.random.randn(10,1), columns=['V'])

In [8]: df0['Key'] = '1st'

In [10]: df1 = pd.DataFrame(data=np.random.randn(10,1), columns=['V'])

In [11]: df1['Key'] = '2nd'

In [13]: df = pd.concat([df0,df1])

In [15]: df.head()
Out[15]:
          V  Key
0  0.042912  1st
1  0.244346  1st
2 -1.250078  1st
3 -1.497983  1st
4  1.144887  1st

In [16]: df.tail()
Out[16]:
          V  Key
5  0.319717  2nd
6  0.643274  2nd
7 -0.868378  2nd
8 -0.108774  2nd
9  0.770334  2nd

In [17]: g = sns.FacetGrid(df, hue='Key')

In [18]: g.map(sns.distplot, 'V', label='Key')
Out[18]: <seaborn.axisgrid.FacetGrid at 0x2b30c93c8a90>

In [19]: g.add_legend()
Out[19]: <seaborn.axisgrid.FacetGrid at 0x2b30c93c8a90>

In [20]: plt.show()

f:id:nekoyukimmm:20151031134603p:plain

hueで選択したカラム名columnを、g.map()のところで、labelで指定する。
で、g.add_legend()をする。
ここは、plt.legend()でもいける。