Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

seaborn factorplot: set series order of display in legend

Seaborn, for some special cases, order the legend sometimes differently than the plotting order:

data = {'group': [-2, -1, 0] * 5,
        'x': range(5)*3,
        'y' : range(15)}
df = pd.DataFrame(data)
sns.factorplot(kind='point', x='x', y='y', hue='group', data=df)

While the plotting sequence is [-2, -1, 0], the legend is listed in order of [-1, -2, 0].

My current workaround is to disable the legend in factorplot and then add the legend afterwards using matplotlib. Is there a better way?

like image 851
user3287545 Avatar asked Feb 12 '15 03:02

user3287545


2 Answers

I think what you're looking for is hue_order = [-2, -1, 0]

df = pd.DataFrame({'group': ['-2','-1','0'] * 5, 'x' : range(5) * 3, 'y' : range(15)})
sns.factorplot(kind = 'point', x = 'x', y= 'y', hue_order = ['-2', '-1', '0'], hue = 'group', data = df)
like image 135
Bo Maxwell Stevens Avatar answered Oct 16 '22 11:10

Bo Maxwell Stevens


I just stumbled across this oldish post. The only answer doesn't seem to work for me but I found a more satisfying solution to change legend order. Although in your examples the legends are set correctly for me, it is possible to change the ordre via the add_legend() method:

df = pd.DataFrame({'group': [-2,-1,0] * 5, 'x' : range(5) * 3, 'y' : range(15)})
ax = sns.factorplot(kind = 'point', x = 'x', y= 'y', hue = 'group', data = df, legend = False)
ax.add_legend(label_order = ['0','-1','-2'])

And for automated numerical sorting:

ax.add_legend(label_order = sorted(ax._legend_data.keys(), key = int))
like image 39
GeorgeDean Avatar answered Oct 16 '22 09:10

GeorgeDean