Как форматировать формат номера оси до тысяч с запятой в 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()
Ответы
Ответ 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()
![enter image description here]()
Ответ 2
Если вам нравится хакерский и короткий, вы можете просто обновить ярлыки
def update_xlabels(ax):
xlabels = [format(label, ',.0f') for label in ax.get_xticks()]
ax.set_xticklabels(xlabels)
update_xlabels(ax)
update_xlabels(ax2)
Ответ 3
Вы можете использовать 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()
![enter image description here]()
Ответ 4
Я всегда нахожусь на этой же странице каждый раз, когда я пытаюсь это сделать. Конечно, другие ответы выполняются, но их нелегко запомнить в следующий раз! ex: import ticker и использовать lambda, custom def и т.д.
Здесь простое решение, если у вас есть оси с именем ax
:
ax.set_yticklabels(['{:,}'.format(int(x)) for x in ax.get_yticks().tolist()])
Ответ 5
Лучший способ, который я нашел для этого, - StrMethodFormatter
:
import matplotlib as mpl
ax.yaxis.set_major_formatter(mpl.ticker.StrMethodFormatter('{x:,.0f}'))
Например:
import pandas as pd
import requests
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()
![введите описание изображения здесь]()