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?
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)
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With