user3287545
user3287545

Reputation: 2061

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?

Upvotes: 21

Views: 28333

Answers (2)

Bo Maxwell Stevens
Bo Maxwell Stevens

Reputation: 341

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)

Upvotes: 24

GeorgeDean
GeorgeDean

Reputation: 93

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

Upvotes: 7

Related Questions