Matplotlib Digit Grouping (decimal separator)

In principle, when creating graphs with matplotlib, the scale along the y axis goes into millions. How do I enable a grouping of digits (i.e., so that 1,000,000 is displayed as 1,000,000) or include a decimal separator?

+3
source share
1 answer

I do not think there is a built-in function for this. (This is what I thought after reading your Q, I just checked and could not find it in the documentation).

In any case, it's easy to collapse your own.

( - .. mpl , , - , - ( ) , , .)

# first code a function to generate the axis labels you want 
# ie, turn numbers greater than 1000 into commified strings (12549 => 12,549)

import locale
locale.setlocale(locale.LC_ALL, 'en_US')
fnx = lambda x : locale.format("%d", x, grouping=True)

from matplotlib import pyplot as PLT
import numpy as NP

data = NP.random.randint(15000, 85000, 50).reshape(25, 2)
x, y = data[:,0], data[:,1]

fig = PLT.figure()
ax1 = fig.add_subplot(111)
ax1.plot(x, y, "ro")
default_xtick = range(20000, 100000, 10000)

# these two lines are the crux:
# create the custom tick labels
new_xtick = map(fnx, default_xtick)
# set those labels on the axis
ax1.set_xticklabels(new_xtick)

PLT.show()
+3

Source: https://habr.com/ru/post/1739549/


All Articles