Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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", 6) g = sns.scatterplot(ax=ax, x="Area", 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)) 

enter image description here

How can I can change the axis format from a number to custom format? For example, 125000 to 125.00K

like image 949
Vinay Avatar asked Dec 12 '18 16:12

Vinay


People also ask

What is the use of Xticks () and Yticks () in plotting?

You can use the xticks() and yticks() functions and pass in an array denoting the actual ticks. On the X-axis, this array starts on 0 and ends at the length of the x array. On the Y-axis, it starts at 0 and ends at the max value of y . You can hard code the variables in as well.

What is SNS set ()?

sns.set() You can also customize seaborn theme or use one of six variations of the default theme. Which are called deep, muted, pastel, bright, dark, and colorblind. # Plot color palette.


1 Answers

IIUC you can format the xticks and set these:

In[60]: #generate some psuedo data df = pd.DataFrame({'num':[50000, 75000, 100000, 125000], 'Rent/Sqft':np.random.randn(4), 'Region':list('abcd')}) df  Out[60]:        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[61]: 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[61]:  

enter image description here

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

see the docs

like image 175
EdChum Avatar answered Sep 24 '22 17:09

EdChum