2015-02-12 133 views
4

Seaborn,对于一些特殊情况,图例中的列表顺序可能与绘图顺序不同。例如,下面的代码:seaborn factorplot:设置图例中显示的系列顺序

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) 

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

+0

有可能是一个更优雅解决方法,但基本问题是seaborn中的一个已知问题:https://github.com/mwaskom/seaborn/issues/340 – mwaskom 2015-02-12 16:06:03

回答

5

我想你要找的是什么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) 
2

我只是碰到这种老气后绊倒了。唯一的答案似乎不适用于我,但我找到了更令人满意的解决方案来更改图例顺序。 虽然你的例子传说是为我设置正确,可以通过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']) 

而对于自动数值排序:

ax.add_legend(label_order = sorted(ax._legend_data.keys(), key = int))