KZiovas
KZiovas

Reputation: 4709

Invert order and color of hue categories using Seaborn

So when I am plotting a box graph and I am using a cotagory in "hue" I get a default order of the categories (Yes and No in my case). I want the boxes to be presented in the reverse order (No Yes) and with the reverse colors. This is my code:

fig=plt.figure(figsize=(12,6))
df2=df[df["AMT_INCOME_TOTAL"]<=df["AMT_INCOME_TOTAL"].median()]
ax = sns.boxplot(x="NAME_FAMILY_STATUS", y="AMT_INCOME_TOTAL", data=df2,hue="FLAG_OWN_REALTY")
plt.legend(bbox_to_anchor=(1.05,1),loc=2, borderaxespad=1,title="Own Property flag")
plt.title('Income Totals per Family Status for Bottom Half of Earners')

enter image description here

I would like to have the "N" category first and with blue color.

Upvotes: 1

Views: 3545

Answers (2)

Prima
Prima

Reputation: 70

just add hue_order on the sns.boxplot()

ax = sns.boxplot(x="NAME_FAMILY_STATUS", y="AMT_INCOME_TOTAL", data=df2,hue="FLAG_OWN_REALTY", hue_order = ['N', 'Y'])

Upvotes: 2

KZiovas
KZiovas

Reputation: 4709

As mentioned above this does the job if you want to explicitly specify the order of the boxes and the hue_order:

fig=plt.figure(figsize=(12,6))
df2=df[df["AMT_INCOME_TOTAL"]<=df["AMT_INCOME_TOTAL"].median()]
ax = sns.boxplot(x="NAME_FAMILY_STATUS", y="AMT_INCOME_TOTAL", data=df2,hue="FLAG_OWN_REALTY",order=['Married',"Civil marriage","Widow","Single / not married","Separated"], hue_order = ['N', 'Y'])
plt.legend(bbox_to_anchor=(1.05,1),loc=2, borderaxespad=1,title="Own Property flag")
plt.title('Income Totals per Family Status for Bottom Half of Earners')

Upvotes: 3

Related Questions