Ice*_*lin 50 python matplotlib
如何更改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()
fal*_*tru 70
使用,的格式说明:
>>> 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()

Ale*_*exG 20
我发现这样做的最好方法是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()
Jar*_*rad 17
每当我尝试这样做时,我总会发现自己在同一页面上.当然,其他答案可以完成工作,但下次不容易记住!例如:导入股票代码并使用lambda,自定义def等.
如果您有一个名为的轴,这是一个简单的解决方案ax:
ax.set_yticklabels(['{:,}'.format(int(x)) for x in ax.get_yticks().tolist()])
如果你喜欢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)
无需导入的简短回答 matplotlib as mpl
plt.gca().yaxis.set_major_formatter(plt.matplotlib.ticker.StrMethodFormatter('{x:,.0f}'))
修改自@AlexG 的回答
您可以使用 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()
