如何格式化seaborn/matplotlib轴刻度标签从数字到成千上万? (125436至125.4K) [英] How to format seaborn/matplotlib axis tick labels from number to thousands or Millions? (125,436 to 125.4K)

查看:555
本文介绍了如何格式化seaborn/matplotlib轴刻度标签从数字到成千上万? (125436至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))

如何将轴格式从数字更改为自定义格式?例如125000至125.00K

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

推荐答案

IIUC,您可以格式化xticks并进行设置:

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]: 

这里的关键是这一行:

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

因此,这会将所有刻度线除以1000,然后格式化它们并设置xtick标签

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

更新 感谢@ScottBoston提出了一种更好的方法:

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

请参见文档

这篇关于如何格式化seaborn/matplotlib轴刻度标签从数字到成千上万? (125436至125.4K)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆