Matplotlib : Comma separated number format for axis

Yes, you can use matplotlib.ticker.FuncFormatter to do this.

Here is the example:

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 = str(x)
    ind = s.index('.')
    return s[:ind] + ',' + s[ind+1:]   # change dot to comma

y_format = tkr.FuncFormatter(func)  # make formatter

x = np.linspace(0,10,501)
y = 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()

This results in the following plot:

funcformatter plot


I know the question is old, but as I currently am searching for similar solutions, I decided to leave a comment for future reference if others need this.

For an alternative solution, use the locale module and activate locale-formatting in matplotlib.

E.g., in major parts of Europe, comma is the desired separator. You can use

#Locale settings
import locale
locale.setlocale(locale.LC_ALL, "deu_deu")
import matplotlib as mpl
mpl.rcParams['axes.formatter.use_locale'] = True

#Generate sample plot
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0,10,501)
y = 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()

to produce the same plot as in Andrey's solution, but you can be sure it behaves correctly also in corner-cases.


I think the question really refers to presenting say 300000 on the y-axis as 300,000.

To borrow from Andrey's answer, with a minor tweak,

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 = '{:0,d}'.format(int(x))
   return s


y_format = tkr.FuncFormatter(func)  # make formatter

x = np.linspace(0,10,501)
y = 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()