如何使用逗号将轴数字格式格式化为千位
- 2025-03-19 08:57:00
- admin 原创
- 52
问题描述:
如何将 x 轴上的数字格式改为 而不是10,000
?10000
理想情况下,我只想做这样的事情:
x = format((10000.21, 22000.32, 10120.54), "#,###")
以下是代码:
import matplotlib.pyplot as plt
# create figure instance
fig1 = plt.figure(1)
fig1.set_figheight(15)
fig1.set_figwidth(20)
ax = fig1.add_subplot(2,1,1)
x = 10000.21, 22000.32, 10120.54
y = 1, 4, 15
ax.plot(x, y)
ax2 = fig1.add_subplot(2,1,2)
x2 = 10434, 24444, 31234
y2 = 1, 4, 9
ax2.plot(x2, y2)
fig1.show()
解决方案 1:
用作,
格式说明符:
>>> format(10000.21, ',')
'10,000.21'
或者你也可以str.format
使用format
:
>>> '{:,}'.format(10000.21)
'10,000.21'
和matplotlib.ticker.FuncFormatter
:
...
ax.get_xaxis().set_major_formatter(
matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))
ax2.get_xaxis().set_major_formatter(
matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))
fig1.show()
解决方案 2:
我发现最好的方法是StrMethodFormatter
:
import matplotlib as mpl
ax.yaxis.set_major_formatter(mpl.ticker.StrMethodFormatter('{x:,.0f}'))
例如:
import pandas as pd
import requests
import matplotlib.pyplot as plt
import matplotlib as mpl
url = 'https://min-api.cryptocompare.com/data/histoday?fsym=BTC&tsym=USDT&aggregate=1'
df = pd.DataFrame({'BTC/USD': [d['close'] for d in requests.get(url).json()['Data']]})
ax = df.plot()
ax.yaxis.set_major_formatter(mpl.ticker.StrMethodFormatter('{x:,.0f}'))
plt.show()
解决方案 3:
每次我尝试这样做时,我总是发现自己处于同样的境地。当然,其他答案也能完成工作,但下次不容易记住!例如:导入 ticker 并使用 lambda、自定义 def 等。
如果您有一个名为的轴,那么这是一个简单的解决方案ax
:
ax.set_yticklabels(['{:,}'.format(int(x)) for x in ax.get_yticks().tolist()])
解决方案 4:
简短回答,无需导入matplotlib as mpl
plt.gca().yaxis.set_major_formatter(plt.matplotlib.ticker.StrMethodFormatter('{x:,.0f}'))
修改自@AlexG 的回答
解决方案 5:
如果你喜欢简短的,你也可以更新标签
def update_xlabels(ax):
xlabels = [format(label, ',.0f') for label in ax.get_xticks()]
ax.set_xticklabels(xlabels)
update_xlabels(ax)
update_xlabels(ax2)
解决方案 6:
您可以使用matplotlib.ticker.funcformatter
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as tkr
def func(x, pos): # formatter function takes tick label and tick position
s = '%d' % x
groups = []
while s and s[-1].isdigit():
groups.append(s[-3:])
s = s[:-3]
return s + ','.join(reversed(groups))
y_format = tkr.FuncFormatter(func) # make formatter
x = np.linspace(0,10,501)
y = 1000000*np.sin(x)
ax = plt.subplot(111)
ax.plot(x,y)
ax.yaxis.set_major_formatter(y_format) # set formatter to needed axis
plt.show()
解决方案 7:
x = [10000.21, 22000.32, 10120.54]
您可以使用列表推导来创建标签列表,然后将它们传递给plt.xticks
。
xlabels = [f'{label:,}' for label in x]
plt.xticks(x, xlabels)
解决方案 8:
我认为最简单的方法:
current_values = plt.gca().get_yticks()
plt.gca().set_yticklabels(['{:,.0f}'.format(x) for x in current_values])
来自:
https ://queirozf.com/entries/matplotlib-examples-number-formatting-for-axes-labels
解决方案 9:
如果您希望原始值以刻度显示,请使用
plt.xticks(ticks=plt.xticks()[0], labels=plt.xticks()[0])
这将防止出现从 3000000 到 1.3 e5 等缩写,并将以刻度显示 3000000(精确值)。
解决方案 10:
对于非逗号分隔符,改进接受的答案,下面的答案将用作SEP
分隔符。
SEP = '.'
ax.get_yaxis().set_major_formatter(
matplotlib.ticker.FuncFormatter(
lambda x, p: str.replace(format(int(x), ','), ',', SEP)
)
)
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD