Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Changing order of seaborn lineplot

I have a small pd.DataFrame that looks like this:

Col1 NumCol
0 10000000
1 7500000
2 12500000
3 37500000
4 110000000
5 65000000

NumCol is actually dollar values.

I want to create a seaborn lineplot, but instead of using the numerical values which create a funky looking axis, I’d like to show dollar values.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

sns.lineplot(data=plot_df, x='Col1', y='NumCol') properly creates:
enter image description here

However, I’d like the axes to show $10,000,000, $7,500,000, etc.
I know I can create a string-representation of the column using

plot_df['NumCol_Str'] = plot_df.NumCol.apply(lambda x : "${:,}".format(x))

Which creates:

Col1 NumCol NumCol_Str
0 10000000 $10,000,000
1 7500000 $7,500,000
2 12500000 $12,500,000
3 37500000 $37,500,000
4 110000000 $110,000,000
5 65000000 $65,000,000

However, when plotting, it changes the order of the columns

sns.lineplot(data=plot_df, x='Col1', y='NumCol_Str')

enter image description here

How can I properly plot the linegraph while keeping the new string notation on the axis?

MRE below:

plot_df = pd.DataFrame.from_dict({'Col1': {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5},
 'NumCol': {0: 10000000,
  1: 7500000,
  2: 12500000,
  3: 37500000,
  4: 110000000,
  5: 65000000}})
plot_df['NumCol_Str'] = plot_df.NumCol.apply(lambda x : "${:,}".format(x))
sns.lineplot(data=plot_df, x='Col1', y='NumCol_Str')
sns.lineplot(data=plot_df, x='Col1', y='NumCol')

>Solution :

Just plot using the numeric values and then change the axis formatter with matplotlib tick formatter:

import matplotlib.ticker as mtick
ax.yaxis.set_major_formatter(mtick.StrMethodFormatter('${x:,.0f}'))

EDIT:
Or even simpler as pointed out by @BigBen:

ax.yaxis.set_major_formatter('${x:,.0f}')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading