Python 如何在 matplotlib 中用逗号将轴号格式格式化为千位?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25973581/
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
How do I format axis number format to thousands with a comma in matplotlib?
提问by IcemanBerlin
How can I change the format of the numbers in the x-axis to be like 10,000instead of 10000?
Ideally, I would just like to do something like this:
如何将 x 轴中数字的格式更改为 like10,000而不是10000?理想情况下,我只想做这样的事情:
x = format((10000.21, 22000.32, 10120.54), "#,###")
Here is the code:
这是代码:
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()
采纳答案by falsetru
Use ,as format specifier:
使用,的格式说明:
>>> format(10000.21, ',')
'10,000.21'
Alternatively you can also use str.formatinstead of format:
或者,您也可以使用str.format代替format:
>>> '{:,}'.format(10000.21)
'10,000.21'
With matplotlib.ticker.FuncFormatter:
与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()


回答by pad
You can use matplotlib.ticker.funcformatter
您可以使用 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()


回答by DanT
If you like it hacky and short you can also just update the labels
如果你喜欢它的hacky和short,你也可以更新标签
def update_xlabels(ax):
xlabels = [format(label, ',.0f') for label in ax.get_xticks()]
ax.set_xticklabels(xlabels)
update_xlabels(ax)
update_xlabels(ax2)
回答by Jarad
I always find myself on this same page everytime I try to do this. Sure, the other answers get the job done, but aren't easy to remember for next time! ex: import ticker and use lambda, custom def, etc.
每次我尝试这样做时,我总是发现自己在同一页面上。当然,其他答案可以完成工作,但下次不容易记住!例如:导入代码并使用 lambda、自定义 def 等。
Here's a simple solution if you have an axes named ax:
如果您有一个名为 的轴,这是一个简单的解决方案ax:
ax.set_yticklabels(['{:,}'.format(int(x)) for x in ax.get_yticks().tolist()])
回答by AlexG
The best way I've found to do this is with StrMethodFormatter:
我发现这样做的最好方法是StrMethodFormatter:
import matplotlib as mpl
ax.yaxis.set_major_formatter(mpl.ticker.StrMethodFormatter('{x:,.0f}'))
For example:
例如:
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()

