Matplotlib.ticker.LogFormatter Class in Python (original) (raw)

Last Updated : 21 Apr, 2020

Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.

matplotlib.ticker.LogFormatter

The matplotlib.ticker.LogFormatter class is used for formatting ticks on a log or symlog scale. It is either instantiated directly or is subclassed.

Syntax: class matplotlib.ticker.LogFormatter(base=10.0, labelOnlyBase=False, minor_thresholds=None, linthresh=None)

Parameters:

Methods of the class:

Example 1:

import numpy as np

import matplotlib.pyplot as plt

from matplotlib.ticker import LogFormatterSciNotation

class CustomTicker(LogFormatterSciNotation):

`` def __call__( self , x, pos = None ):

`` if x not in [ 0.1 , 1 , 10 ]:

`` return LogFormatterSciNotation.__call__( self , x, pos = None )

`` else :

`` return "{x:g}" . format (x = x)

fig = plt.figure(figsize = [ 7 , 7 ])

ax = fig.add_subplot( 111 )

ax.set_yscale( 'log' )

ax.set_xscale( 'log' )

ax.plot(np.logspace( - 4 , 4 ), np.logspace( - 4 , 4 ))

ax.xaxis.set_major_formatter(CustomTicker())

plt.show()

Output:

Example 2:

import matplotlib.pyplot as plt

from matplotlib.ticker import LogFormatter

import numpy as np

fig, axes = plt.subplots( 4 , figsize = ( 12 , 24 ))

dt = 0.01

t = np.arange(dt, 20.0 , dt)

axes[ 0 ].semilogx(t, np.exp( - t / 5.0 ))

axes[ 0 ].set_xlim([ 0 , 25 ])

axes[ 0 ].grid()

xlims = [[ 0 , 25 ], [ 0.2 , 8 ], [ 0.6 , 0.9 ]]

for ax, xlim in zip (axes[ 1 :], xlims):

`` ax.semilogx(t, np.exp( - t / 5.0 ))

`` formatter = LogFormatter(labelOnlyBase = False ,

`` minor_thresholds = ( 2 , 0.4 ))

`` ax.get_xaxis().set_minor_formatter(formatter)

`` ax.set_xlim(xlim)

`` ax.grid()

plt.show()

Output: