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

标签 python matplotlib seaborn

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

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

最佳答案

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

这里的关键是这一行:

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

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

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

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

参见 docs

关于python - 如何将 seaborn/matplotlib 轴刻度标签从数字格式化为数千或数百万? (125,436 至 125.4K),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53747298/

相关文章:

python - 无法找到 python 字节码解释器的 gdb 框架

python - MatPlotLib FuncAnimation 不适用于非零间隔或 blit=True

python - 模块中的条件导入

python - 如何并排绘制 2 个 seaborn lmplots?

python - 在 seaborn 中将箱线图转换为散点图

python - for 循环内部或外部 if 语句的复杂性

python - PostgreSQL:创建扩展 plpythonu 查询在 Ubuntu 19.10 和 PostgreSQL 10.10 上不起作用

python - 如何使用 pdfpages 将数据框添加到 pdf 文件

python - 在 Python 中绘制分类数据的三个维度

python - 如何设置PythonPath/UDF_Modules?