Matplotlib pyplot axes formatter

I have an image:

enter image description here

Here on the y axis, I would like to get 5x10^-5 4x10^-5 , etc. instead of 0.00005 0.00004 .

I have tried so far:

 fig = plt.figure() ax = fig.add_subplot(111) y_formatter = matplotlib.ticker.ScalarFormatter(useOffset=True) ax.yaxis.set_major_formatter(y_formatter) ax.plot(m_plot,densities1,'-ro',label='0.0<z<0.5') ax.plot(m_plot,densities2, '-bo',label='0.5<z<1.0') ax.legend(loc='best',scatterpoints=1) plt.legend() plt.show() 

This does not work. The document page for tickers does not seem to give a direct answer.

+8
python matplotlib axes ticker
source share
1 answer

You can use matplotlib.ticker.FuncFormatter to select the format of your ticks using a function, as shown in the code example below. In fact, the whole function converts input (float) to exponential notation, and then replaces "e" with "x10 ^", so you get the format you want.

 import matplotlib.pyplot as plt import matplotlib.ticker as tick import numpy as np x = np.linspace(0, 10, 1000) y = 0.000001*np.sin(10*x) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(x, y) def y_fmt(x, y): return '{:2.2e}'.format(x).replace('e', 'x10^') ax.yaxis.set_major_formatter(tick.FuncFormatter(y_fmt)) plt.show() 

image

If you want to use exponential notation (i.e. 5.0e-6.0), then there is a much matplotlib.ticker.FormatStrFormatter solution in which you use matplotlib.ticker.FormatStrFormatter to select a format string, as shown below. The string format is specified by standard Python string formatting rules.

 ... y_fmt = tick.FormatStrFormatter('%2.2e') ax.yaxis.set_major_formatter(y_fmt) ... 
+8
source share

All Articles