JavaScript
x
11
11
1
import matplotlib.pyplot as plt
2
import matplotlib.ticker as ticker
3
import seaborn as sns
4
import pandas as pd
5
sns.set(style="darkgrid")
6
fig, ax = plt.subplots(figsize=(8, 5))
7
palette = sns.color_palette("bright", 6)
8
g = sns.scatterplot(ax=ax, x="Area", y="Rent/Sqft", hue="Region", marker='o', data=df, s=100, palette= palette)
9
g.legend(bbox_to_anchor=(1, 1), ncol=1)
10
g.set(xlim = (50000,250000))
11
How can I can change the axis format from a number to custom format? For example, 125000 to 125.00K
Advertisement
Answer
IIUC you can format the xticks and set these:
JavaScript
1
28
28
1
In[60]:
2
#generate some psuedo data
3
df = pd.DataFrame({'num':[50000, 75000, 100000, 125000], 'Rent/Sqft':np.random.randn(4), 'Region':list('abcd')})
4
df
5
6
Out[60]:
7
num Rent/Sqft Region
8
0 50000 0.109196 a
9
1 75000 0.566553 b
10
2 100000 -0.274064 c
11
3 125000 -0.636492 d
12
13
In[61]:
14
import matplotlib.pyplot as plt
15
import matplotlib.ticker as ticker
16
import seaborn as sns
17
import pandas as pd
18
sns.set(style="darkgrid")
19
fig, ax = plt.subplots(figsize=(8, 5))
20
palette = sns.color_palette("bright", 4)
21
g = sns.scatterplot(ax=ax, x="num", y="Rent/Sqft", hue="Region", marker='o', data=df, s=100, palette= palette)
22
g.legend(bbox_to_anchor=(1, 1), ncol=1)
23
g.set(xlim = (50000,250000))
24
xlabels = ['{:,.2f}'.format(x) + 'K' for x in g.get_xticks()/1000]
25
g.set_xticklabels(xlabels)
26
27
Out[61]:
28
The key bit here is this line:
JavaScript
1
3
1
xlabels = ['{:,.2f}'.format(x) + 'K' for x in g.get_xticks()/1000]
2
g.set_xticklabels(xlabels)
3
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:
JavaScript
1
2
1
ax.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:,.2f}'.format(x/1000) + 'K'))
2
see the docs