seaborn factorplot:设置图例中显示的系列顺序

use*_*545 7 python matplotlib legend seaborn

Seaborn,对于某些特殊情况,图例中的列表顺序可能与绘图顺序不同.例如,以下代码:

df = pds.DataFrame({'group': [-2,-1,0] * 5, 'x' : range(5) * 3, 'y' : range(15)})
sbn.factorplot(kind = 'point', x = 'x', y= 'y', hue = 'group', data = df)
Run Code Online (Sandbox Code Playgroud)

绘图序列在[-2,-1,0]的组中,但图例按[-1,-2,0]的顺序列出.(前两个交换,可能是由于字符串内部排序而不是数字).我目前的解决方法是在factorplot中禁用图例,然后使用matplotlib语法放置图例.只是想知道是否有更好的方法来做这个比我的解决方法.

小智 8

我想你要找的是 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)
Run Code Online (Sandbox Code Playgroud)


Geo*_*ean 6

我刚刚偶然发现了这篇旧帖子。唯一的答案似乎对我不起作用,但我找到了一个更令人满意的解决方案来更改图例顺序。尽管在您的示例中,图例为我设置正确,但可以通过以下add_legend()方法更改顺序:

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'])
Run Code Online (Sandbox Code Playgroud)

对于自动数字排序:

ax.add_legend(label_order = sorted(ax._legend_data.keys(), key = int))
Run Code Online (Sandbox Code Playgroud)