vspadotto
vspadotto

Reputation: 81

Change order of categorical xaxis in Seaborn

I have a simple df with the Income Category and Credit Limit. When plotting using seaborn, I keep getting an unwanted order in the x-axis. What is the simplest option to "force" the plot to be in the order defined in my new_order?

new_order = ['40k','40k-60k','60k-80k','80k-120k','120k']

sns.lineplot(data=dff, x="Income_Category", y="Credit_Limit")

enter image description here

Upvotes: 0

Views: 550

Answers (1)

David Erickson
David Erickson

Reputation: 16683

You could use some pandas / regex with str.extract() to extroact the numbers, so that you can sort by them. Then, use the index as the x-axis and override the values. Otherwise, seaborn will automatically set the x-axis to the values 0-120, but really you want different categories instead of a numerical axis:

dff = pd.DataFrame({'Income_Category' : ['120k', '40k', '40k-60k', '60k-80k', '80k-120k'], 'Credit_Limit' : [20000, 4000, 6000, 11000, 16000]})
fig, ax = plt.subplots()
new_order = ['40k','40k-60k','60k-80k','80k-120k','120k']
dff['Income_Category'] = ((dff['Income_Category'].str.extract('-(\d+)', expand=False).astype(float))
                 .fillna(dff['Income_Category'].str.extract('(\d+)', expand=False).astype(float) + 1))
dff = dff.sort_values('Income_Category')
sns.lineplot(data=dff, x=dff.index, y="Credit_Limit", ax=ax)
ax.set_xticks(dff.index)
ax.set_xticklabels(new_order)
plt.show()

enter image description here

Upvotes: 1

Related Questions