使用Seaborn反转色调类别的顺序和颜色

2024-10-01 00:20:24 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,当我绘制一个方框图,并且在“色调”中使用一个cotagory时,我会得到一个默认的类别顺序(在我的例子中是和否)。我希望盒子以相反的顺序(否是)和相反的颜色呈现。这是我的代码:

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

我想先用蓝色的“N”类


Tags: df顺序title绘制plt色调类别例子
2条回答

如上所述,如果要明确指定框的顺序和色调顺序,则此操作将执行:

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

只需在sns.boxplot()上添加色调顺序

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

相关问题 更多 >