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

ni65a41a  于 11个月前  发布在  其他
关注(0)|答案(5)|浏览(113)
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

mwkjh3gx

mwkjh3gx1#

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

字符串
x1c 0d1x的数据
这里的关键是这一行:

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

eqzww0vc

eqzww0vc2#

以标准单位格式化刻度标签的规范方法是使用EngFormatter。在matplotlib文档中也有an example
参见Tick locating and formatting
在这里,它可能看起来如下。

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

字符串


的数据

1tuwyuhd

1tuwyuhd3#

使用**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

字符串
感谢EdChum上面的回答让我有90%。

xvw2m8pv

xvw2m8pv4#

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

from matplotlib.ticker import FuncFormatter

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

字符串

smdncfj3

smdncfj35#

我们可以使用以下API:ax.get_xticklabels()get_text()ax.set_xticklabels
例如,

xlabels = ['{:.2f}k'.format(float(x.get_text().replace('−', '-')))/1000 for x in g.get_xticklabels()]
g.set_xticklabels(xlabels)

字符串

相关问题