Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib : Comma separated number format for axis

I am attempting to change the format of my axis to be comma seperated in Matplotlib running under Python 2.7 but am unable to do so.

I suspect that I need to use a FuncFormatter but I am at a bit of a loss.

Can anyone help?

like image 205
Patrick A Avatar asked Nov 25 '11 16:11

Patrick A


People also ask

How do I avoid scientific notation in Matplotlib?

MatPlotLib with Python To prevent scientific notation, we must pass style='plain' in the ticklabel_format method.

Can you format the numbers on the Y axis so they look like dollar amounts?

Use a FormatStrFormatter to prepend dollar signs on y axis labels. The use of the following functions, methods, classes and modules is shown in this example: matplotlib. pyplot.


1 Answers

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

like image 185
Andrey Sobolev Avatar answered Oct 26 '22 14:10

Andrey Sobolev