Thursday, June 11, 2026
HomeLanguagesMatplotlib.ticker.IndexFormatter class in Python

Matplotlib.ticker.IndexFormatter class in Python

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.IndexFormatter

The matplotlib.ticker.IndexFormatter class is a subclass of matplotlib.ticker class and is used to format the position x that is the nearest i-th label where i = int(x + 0.5). The positions with i len(list) have 0 tick labels.

Syntax: class matplotlib.ticker.IndexFormatter(labels)

Parameter :

  • labels: It is a list of labels.

Example 1:




import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
  
   
# create dummy data    
x = ['str{}'.format(k) for k in range(20)]
y = np.random.rand(len(x))
   
# create an IndexFormatter 
# with labels x
x_fmt = mpl.ticker.IndexFormatter(x)
   
fig,ax = plt.subplots()
  
ax.plot(y)
  
# set our IndexFormatter to be
# responsible for major ticks
ax.xaxis.set_major_formatter(x_fmt)


Output:

Example 2:




from matplotlib.ticker import IndexFormatter, IndexLocator
import pandas as pd
import matplotlib.pyplot as plt
  
  
years = range(2015, 2018)
fields = range(4)
days = range(4)
bands = ['R', 'G', 'B']
  
index = pd.MultiIndex.from_product(
    [years, fields], names =['year', 'field'])
  
columns = pd.MultiIndex.from_product(
    [days, bands], names =['day', 'band'])
  
df = pd.DataFrame(0, index = index, columns = columns)
  
df.loc[(2015, ), (0, )] = 1
df.loc[(2016, ), (1, )] = 1
df.loc[(2017, ), (2, )] = 1
ax = plt.gca()
plt.spy(df)
  
xbase = len(bands)
xoffset = xbase / 2
xlabels = df.columns.get_level_values('day')
  
ax.xaxis.set_major_locator(IndexLocator(base = xbase,
                                        offset = xoffset))
  
ax.xaxis.set_major_formatter(IndexFormatter(xlabels))
  
plt.xlabel('Day')
ax.xaxis.tick_bottom()
  
ybase = len(fields)
yoffset = ybase / 2
ylabels = df.index.get_level_values('year')
  
ax.yaxis.set_major_locator(IndexLocator(base = ybase, 
                                        offset = yoffset))
  
ax.yaxis.set_major_formatter(IndexFormatter(ylabels))
  
plt.ylabel('Year')
  
plt.show()


Output:

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6897 POSTS0 COMMENTS
Nicole Veronica
12013 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6963 POSTS0 COMMENTS