How to format seaborn/matplotlib axis tick labels from number to thousands or Millions? (125,436 to 125.4K)

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to format seaborn/matplotlib axis tick labels from number to thousands or Millions? (125,436 to 125.4K) in Python. So Here I am Explain to you all the possible Methods here.

How to format seaborn/matplotlib axis tick labels from number to thousands or Millions? (125,436 to 125.4K)?

1. How to format seaborn/matplotlib axis tick labels from number to thousands or Millions? (125,436 to 125.4K)?

We could used the APIs: ax.get_xtricklabels() , get_text() and ax.set_xtricklabels do it.

2. format seaborn/matplotlib axis tick labels from number to thousands or Millions? (125,436 to 125.4K)

We could used the APIs: ax.get_xtricklabels() , get_text() and ax.set_xtricklabels do it.

Method 1

IIUC you can format the xticks and set these:

In:
#generate some psuedo data
df = pd.DataFrame({'num':[50000, 75000, 100000, 125000], 'Rent/Sqft':np.random.randn(4), 'Region':list('abcd')})
df

Out:
num  Rent/Sqft Region
0   50000   0.109196      a
1   75000   0.566553      b
2  100000  -0.274064      c
3  125000  -0.636492      d

In:
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import seaborn as sns
import pandas as pd
sns.set(style="darkgrid")
fig, ax = plt.subplots(figsize=(8, 5))
palette = sns.color_palette("bright", 4)
g = sns.scatterplot(ax=ax, x="num", y="Rent/Sqft", hue="Region", marker='o', data=df, s=100, palette= palette)
g.legend(bbox_to_anchor=(1, 1), ncol=1)
g.set(xlim = (50000,250000))
xlabels = ['{:,.2f}'.format(x) + 'K' for x in g.get_xticks()/1000]
g.set_xticklabels(xlabels)

Out:

The key bit here is this line:

xlabels = ['{:,.2f}'.format(x) + 'K' for x in g.get_xticks()/1000]
g.set_xticklabels(xlabels)

So this divides all the ticks by 1000 and then formats them and sets the xtick labels

UPDATE Thanks to @ScottBoston who has suggested a better method:

ax.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:,.2f}'.format(x/1000) + 'K'))

Method 2

We could used the APIs: ax.get_xtricklabels() , get_text() and ax.set_xtricklabels do it.

e.g,

xlabels = ['{:.2f}k'.format(float(x.get_text().replace('−', '-')))/1000 for x in g.get_xticklabels()]
g.set_xticklabels(xlabels)

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.