user308827
user308827

Reputation: 22031

Incorrect legend labels in python seaborn plots

enter image description here

The above plot is made using seaborn in python. However, not sure why some of the legend circles are filled in with color and others are not. This is the colormap I am using:

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)

--EDIT:

Is there a way the circles can be filled? The reason they are not filled is that they might not have data in this particular plot

Upvotes: 4

Views: 2738

Answers (1)

keredson
keredson

Reputation: 3087

The circles are not filled in when there is no data, as I think you've already deduced. But it can be forced by manipulating the legend object.

Full example:

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

The important part is the manipulation of the handle objects in legend at the end (in the for loop).

This will generate:

enter image description here

Compared to the original (without the for loop):

enter image description here

EDIT: Now less hacky thanks to suggestions from comments!

Upvotes: 7

Related Questions