简体   繁体   中英

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.

sns.lineplot(data=plot_df, x='Col1', y='NumCol') properly creates: 在此处输入图像描述

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

在此处输入图像描述

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM