2017-11-28 1 views
-1

Seabornプロットで凡例を制御およびカスタマイズする方法に関するガイダンスを探していますが、見つけられません。私は女性として男性とFとMを定義できるようにしたいと思います。この例ではSeaborn-Pythonで凡例を制御する方法

surveys_by_year_sex_long 

    year sex wgt 
0 2001 F 36.221914 
1 2001 M 36.481844 
2 2002 F 34.016799 
3 2002 M 37.589905 

%matplotlib inline 
from matplotlib import * 
from matplotlib import pyplot as plt 
import seaborn as sn 

sn.factorplot(x = "year", y = "wgt", data = surveys_by_year_sex_long, hue = "sex", kind = "bar", legend_out = True, 
      palette = sn.color_palette(palette = ["SteelBlue" , "Salmon"]), hue_order = ["M", "F"]) 
plt.xlabel('Year') 
plt.ylabel('Weight') 
plt.title('Average Weight by Year and Sex') 

enter image description here

、代わりにセックス:

は私が再現可能な例を提供し、問題がより具体化するために、伝説のタイトルとしてセックスをする。

あなたのアドバイスは高く評価されます。

答えて

0

まず、seabornによって作成された凡例にアクセスするには、seaborn呼び出しで行う必要があります。

g = sns.factorplot(...) 
legend = g._legend 

この凡例は、次に操作することができる凡例の文字列は、従って凡例プロット

と重なることになる、以前よりも大きいので、

legend.set_title("Sex") 
for t, l in zip(legend.texts,("Male", "Female")): 
    t.set_text(l) 

結果は完全に喜ばないenter image description here

したがって、余裕を少し調整する必要があります。

g.fig.subplots_adjust(top=0.9,right=0.7) 

enter image description here

1

海賊のプロットのラベルを変更すると、ちょっとトリッキーになってしまいました。最も簡単な解決策は、値と列名をマッピングすることによって入力データ自体を変更することです。次のように新しいデータフレームを作成し、同じプロットコマンドを使用することができます。

data = surveys_by_year_sex_long.rename(columns={'sex': 'Sex'}) 
data['Sex'] = data['Sex'].map({'M': 'Male', 'F': 'Female'}) 
sn.factorplot(
    x = "year", y = "wgt", data = data, hue = "Sex", 
    kind = "bar", legend_out = True, 
    palette = sn.color_palette(palette = ["SteelBlue" , "Salmon"]), 
    hue_order = ["Male", "Female"]) 

Updated names

うまくいけば、これは何が必要ありません。潜在的な問題は、データセットが大きい場合、この方法でまったく新しいデータフレームを作成するとオーバーヘッドが増加することです。

関連する問題