How do I format axis number format to thousands with a comma in matplotlib?
How can I change the format of the numbers in the x-axis to be like 10,000
instead of 10000
?
Ideally, I would just like to do something like this:
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()
Use ,
as format specifier:
>>> format(10000.21, ',')
'10,000.21'
Alternatively you can also use str.format
instead of format
:
>>> '{:,}'.format(10000.21)
'10,000.21'
With 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()
The best way I've found to do this is with 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()
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.
Here's a simple solution if you have an axes named ax
:
ax.set_yticklabels(['{:,}'.format(int(x)) for x in ax.get_yticks().tolist()])