python seaborn图中的图例标签不正确

use*_*827 4 python matplotlib seaborn

在此输入图像描述

上面的情节是用python中的seaborn制作的.但是,不确定为什么有些传奇圈子用颜色填充而其他圈子没有.这是我使用的色彩映射:

sns.color_palette("Set2", 10)

g = sns.factorplot(x='month', y='vae_factor', hue='ad_name', col='crop', data=df_sub_panel,
                   col_wrap=3, size=5, lw=0.5, ci=None, capsize=.2, palette=sns.color_palette("Set2", 10),
                   sharex=False, aspect=.9, legend_out=False)
g.axes[0].legend(fancybox=None)
Run Code Online (Sandbox Code Playgroud)

- 编辑:

有没有办法可以填充圆圈?他们没有填补的原因是他们可能没有这个特定情节中的数据

ker*_*son 6

当没有数据时,圈子没有被填充,因为我认为你已经推断过了.但是可以通过操纵图例对象来强制它.

完整示例:

import pandas as pd
import seaborn as sns

df_sub_panel = pd.DataFrame([
  {'month':'jan', 'vae_factor':50, 'ad_name':'China', 'crop':False},
  {'month':'feb', 'vae_factor':60, 'ad_name':'China', 'crop':False},
  {'month':'feb', 'vae_factor':None, 'ad_name':'Mexico', 'crop':False},
])

sns.color_palette("Set2", 10)

g = sns.factorplot(x='month', y='vae_factor', hue='ad_name', col='crop', data=df_sub_panel,
                   col_wrap=3, size=5, lw=0.5, ci=None, capsize=.2, palette=sns.color_palette("Set2", 10),
                   sharex=False, aspect=.9, legend_out=False)

# fill in empty legend handles (handles are empty when vae_factor is NaN)
for handle in g.axes[0].get_legend_handles_labels()[0]:
  if not handle.get_facecolors().any():
    handle.set_facecolor(handle.get_edgecolors())

legend = g.axes[0].legend(fancybox=None)

sns.plt.show()
Run Code Online (Sandbox Code Playgroud)

最重要的部分是最后操作handle对象legend(在for循环中).

这将产生:

在此输入图像描述

与原始(没有for循环)相比:

在此输入图像描述

编辑:由于评论的建议,现在不那么hacky!