Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On matplotlib logarithmic axes labels

Dear matplotlib community,

I have a very quick question regarding logarithmic axis labelling that I'm sure one of you could answer at the drop of a hat.

Essentially I have a log axis in matplotlib with labels of 10^-2, 10^-1, 10^0, 10^1, 10^2 etc

However, I would like 0.01, 0.1, 1, 10, 100.

Could anyone guide me on this. I have tried a few options, such as:

ax.set_xticks([0.01,0.1,1,10,100])

ax.set_xlabels([0.01,0.1,1,10,100])

Any pro tips would be greatly appreciated!

like image 829
GCien Avatar asked Sep 21 '25 06:09

GCien


2 Answers

I think you want ax.xaxis.set_major_formatter(FormatStrFormatter("%g")), as in:

x=[0.1,1,10,100,1000]
y=[-1,0,1,2,3]
fig,ax=plt.subplots()
ax.plot(x,y,'.-')
ax.set_xscale('log')
ax.xaxis.set_major_formatter(FormatStrFormatter("%g"))

Example output: example output from log plot axis label format change

like image 87
EL_DON Avatar answered Sep 22 '25 20:09

EL_DON


A nice way is to use the FuncFormatter class of the matplotlib.ticker module. In conjunction with a custom function definition of your own making, this can help to customise your ticks to the exact way you want them. This particular bit of code works well with the logarithmic scale employed by matplotlib.

import numpy as np
import matplotlib.pylab as plt

x = np.linspace(-10,10)
y = np.exp(x)

plt.close('all')

fig,ax = plt.subplots(1,1)
ax.plot(x,y,'bo')
ax.set_yscale('log')

#Placed the import/function definitions here to emphasize
#the working lines of code for this particular task.
from matplotlib.ticker import FuncFormatter

def labeller(x, pos):
    """
    x is the tick value, pos is the position. These args are needed by 
    FuncFormatter.
    """

    if x < 1:
        return '0.'+'0'*(abs(int(np.log10(x)))-1)+\
                format(x/10**(np.floor(np.log10(x))),'.0f')
    else:
        return format(x,'.0f')

#FuncFormatter class instance defined from the function above
custom_formatter = FuncFormatter(labeller)

ax.yaxis.set_major_formatter(custom_formatter)
plt.show()

Result:

enter image description here

like image 21
SP805 Avatar answered Sep 22 '25 21:09

SP805