Python 如何将 seaborn/matplotlib 轴刻度标签从数字格式化为数千或数百万?(125,436 到 125.4K)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53747298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:22:04  来源:igfitidea点击:

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

pythonmatplotlibseaborn

提问by Vinay

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

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

采纳答案by EdChum

IIUC you can format the xticks and set these:

IIUC 您可以格式化 xticks 并设置这些:

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 1000and then formats them and sets the xtick labels

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

UPDATEThanks to @ScottBoston who has suggested a better method:

更新感谢@ScottBoston,他提出了一个更好的方法:

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

see the docs

查看文档

回答by ImportanceOfBeingErnest

The canonical way of formatting the tick labels in the standard units is to use an EngFormatter. There is also an examplein the matplotlib docs.

以标准单位格式化刻度标签的规范方法是使用EngFormatter. matplotlib 文档中还有一个示例

Here it might look as follows.

它可能如下所示。

import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import seaborn as sns
import pandas as pd

df = pd.DataFrame({"xaxs" : np.random.randint(50000,250000, size=20),
                   "yaxs" : np.random.randint(7,15, size=20),
                   "col"  : np.random.choice(list("ABC"), size=20)})

fig, ax = plt.subplots(figsize=(8, 5))    
palette = sns.color_palette("bright", 6)
sns.scatterplot(ax=ax, x="xaxs", y="yaxs", hue="col", data=df, 
                marker='o', s=100, palette="magma")
ax.legend(bbox_to_anchor=(1, 1), ncol=1)
ax.set(xlim = (50000,250000))

ax.xaxis.set_major_formatter(ticker.EngFormatter())

plt.show()

enter image description here

在此处输入图片说明

回答by Boris Yakubchik

Using Seabornwithoutimporting matplotlib:

使用Seaborn而不导入matplotlib

import seaborn as sns
sns.set()

chart = sns.relplot(x="x_val", y="y_val", kind="line", data=my_data)

ticks = chart.axes[0][0].get_xticks()

xlabels = ['$' + '{:,.0f}'.format(x) for x in ticks]

chart.set_xticklabels(xlabels)
chart.fig

Thank you to EdChum's answer above for getting me 90% there.

感谢上面 EdChum 的回答,让我达到了 90%。

回答by Yaakov Bressler

Here's how I'm solving this:(similar to ScottBoston)

这是我解决这个问题的方法:(类似于 ScottBoston)

from matplotlib.ticker import FuncFormatter

f = lambda x, pos: f'{x/10**3:,.0f}K'
ax.xaxis.set_major_formatter(FuncFormatter(f))