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:
JavaScript
x
2
1
x = format((10000.21, 22000.32, 10120.54), "#,###")
2
Here is the code:
JavaScript
1
22
22
1
import matplotlib.pyplot as plt
2
3
# create figure instance
4
fig1 = plt.figure(1)
5
fig1.set_figheight(15)
6
fig1.set_figwidth(20)
7
8
ax = fig1.add_subplot(2,1,1)
9
10
x = 10000.21, 22000.32, 10120.54
11
12
y = 1, 4, 15
13
ax.plot(x, y)
14
15
ax2 = fig1.add_subplot(2,1,2)
16
17
x2 = 10434, 24444, 31234
18
y2 = 1, 4, 9
19
ax2.plot(x2, y2)
20
21
fig1.show()
22
Advertisement
Answer
Use ,
as format specifier:
JavaScript
1
3
1
>>> format(10000.21, ',')
2
'10,000.21'
3
Alternatively you can also use str.format
instead of format
:
JavaScript
1
3
1
>>> '{:,}'.format(10000.21)
2
'10,000.21'
3
With matplotlib.ticker.FuncFormatter
:
JavaScript
1
7
1
2
ax.get_xaxis().set_major_formatter(
3
matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))
4
ax2.get_xaxis().set_major_formatter(
5
matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))
6
fig1.show()
7