Issue
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?
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}')
Answered By - Toby Petty
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.