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:
| importnumpy as np importmatplotlib.pyplot as plt importmatplotlib as mpl  Â  Â# create dummy data     x =['str{}'.format(k) fork inrange(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:
| frommatplotlib.ticker importIndexFormatter, IndexLocator importpandas as pd importmatplotlib.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, )] =1df.loc[(2016, ), (1, )] =1df.loc[(2017, ), (2, )] =1ax =plt.gca() plt.spy(df)  Âxbase =len(bands) xoffset =xbase /2xlabels =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 /2ylabels =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:
 
				 
					



