Michael Roberts Michael Roberts - 1 year ago 202
Python Question

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:



Any pro tips would be greatly appreciated!

Answer Source

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)


fig,ax = plt.subplots(1,1)

#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 

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

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



enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download