Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python + matplotlib: use locale to format y axis

I want to format my y axis using matplotlib in python 2.7. This is what I tried:

ax.yaxis.get_major_formatter().set_useLocale()

to format my y axis using . as thousands separator. Instead of having 10000, I'd like to have 10.000, and so on... but I can't find any example on how this work...

I could not find the documentation, on this page here there is no example or further documentation: http://matplotlib.org/api/ticker_api.html#matplotlib.ticker.ScalarFormatter.set_useLocale

Or any other idea on how to format my axis?

thanks

like image 624
otmezger Avatar asked Nov 22 '13 00:11

otmezger


People also ask

How do I change the Y axis scale in Python?

To change the range of X and Y axes, we can use xlim() and ylim() methods.

What is the use of Xticks () and Yticks () in plotting?

The xticks() and yticks() function takes a list object as argument. The elements in the list denote the positions on corresponding action where ticks will be displayed. This method will mark the data points at the given positions with ticks.

How do you define Y axis in Python?

Practical Data Science using Python To specify the value of axes, create a list of characters. Use xticks and yticks method to specify the ticks on the axes with x and y ticks data points respectively. Plot the line using x and y, color=red, using plot() method. Make x and y margin 0.

Why is %Matplotlib inline?

The line magic command %matplotlib inline enables the drawing of matplotlib figures in the IPython environment. Once this command is executed in any cell, then for the rest of the session, the matplotlib plots will appear directly below the cell in which the plot function was called.


1 Answers

I believe that you are looking for more control than perhaps set_useLocale() can offer. Therefore, drawing upon the example given here, I've used FuncFormatter with a simple function. The comma_format function inserts the y-axis labels with a comma as a thousands separator and then replaces the commas with periods. In this way, the y-axis labels can be formatted rather easily.

from pylab import *
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

def comma_format(x, p):
    return format(x, "6,.0f").replace(",", ".")

ax = subplot(111)
xx = np.arange(0,20,1)
yy = np.arange(1000,10000,450)
ax.get_yaxis().set_major_formatter(ticker.FuncFormatter(comma_format))
plt.scatter(xx,yy)
plt.show()

enter image description here

like image 174
cosmosis Avatar answered Nov 03 '22 07:11

cosmosis