tmart
tmart

Reputation: 3

Seaborn Boxplot Legend colors mismatched after setting order in plot

I have the same issue as a previous post (legend icons are not right shape). Adjusting hue per Trenton's comment in that thread (setting hue to be same as x value) worked. However, I am also trying to set the order of the boxes using order = [my manual list]. Now the colors in the legend are different from the colors in the boxes themselves. Additionally, this seems to have altered the widths and alignment of the boxes themselves.

Any advice would be appreciated.

edu_order = ['No formal education past high school','Some college/university study without earning a bachelor’s degree','Bachelor’s degree', 'Master’s degree', 'Professional doctorate','Doctoral degree','I prefer not to answer']
    
    plt.figure(figsize=(10,9))
    ax = sns.boxplot(x='Q4', y = 'Q25',
              hue = 'Q4',
              order = edu_order,       
                     data=edu)
                
    ax.set(xlabel=None)
    #ax.set(xticklabels=[])
    
    plt.yscale('log')
    plt.xticks(rotation=90)
    
    #legend_label = ['High School','Some Secondary','Bachelor’s', 'Master’s', 'Professional PhD','PhD','I prefer not to answer']
    #legend_label = ['No formal education past high school','Some college/university study without earning a bachelor’s degree','Bachelor’s degree', 'Master’s degree', 'Professional doctorate','Doctoral degree','I prefer not to answer']
    #legend_label = ['Bachelor’s degree', 'Master’s degree', 'Doctoral degree',       'I prefer not to answer', 'No formal education past high school',       'Some college/university study without earning a bachelor’s degree',       'Professional doctorate']
    legend_label = edu_order
    n=0
    for i in legend_label:
        ax.legend_.texts[n].set_text(i)
        n +=1
    sns.move_legend(ax, "best")
    
    plt.show()

Here's a progression of the plots: basic plot without legend

with legend. colors are correct. alignment/sizing off

ordered and legend text matches but colors wrong. alignment/sizing off

Upvotes: 0

Views: 1404

Answers (1)

relent95
relent95

Reputation: 4731

That's because you incorrectly updated labels of the legend that was created by Seaborn. Don't do that.

Instead use hue_order like this.

sns.boxplot(data=edu,
  x='Q4', y='Q25', hue='Q4',
  order=edu_order, hue_order=edu_order)

Upvotes: 1

Related Questions