Setting Ticks and Tick Labels in Matplotlib

In Matplotlib library the Ticks are the markers that are used to denote the data points on the axis.

  • It is important to note that in the matplotlib library the task of spacing points on the axis is done automatically.
  • The default tick locators and formatters in matplotlib are also good and are sufficient for most of the use-cases.
  • This task can be done explicitly with the help of two functions: set_xticks() and set_yticks()
  • Both these functions will take a list object as its arguments. The elements that are present in the list denote the positions and the values that will be shown on these tick positions is set using the set_xticklables() and set_yticklabels() functions.

For Example:


The above code will mark the data points at the given positions with ticks.

Then to set the labels corresponding to tick marks, we use the set_xticklabels() and set_yticklabels() functions respectively.

ax.set_xlabels(['two', 'four', 'six', 'eight', 'twelve'])

Now with the help of the above command, It will display the text labels just below the markers on the x-axis.

Custom Ticks and Tick labels

Now let us take a look at an example of setting ticks and tick labels in Matplotlib Library:

import matplotlib.pyplot as plt
import numpy as np
import math

x = np.arange(0, math.pi*2, 0.04)
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) 
y = np.cos(x)
ax.plot(x, y)

# this will label the x axis
# setting title of plot
# set the tick marks for x axis
# provide name to the x axis tick marks

Here is the output:

set axis ticks and tick labels for matplotlib plot

In the above code, you must have noticed the function set_xlabel(), this function is used to specify a label for the X axis, in our case we are showing angles on x axis, hence the name angles.

Then we have specified the tick marks explicitly and have also provided labels for the tick marks.

This is a good technique to customize your graphs completely.

Follow Us On