Setting Ticks and Tick Labels in Matplotlib
In this tutorial, we will learn how to set ticks on the axis and specify custom tick labels to make your matplotlib graph more readable and intuitive.
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:
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
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_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 ax.set_xlabel('angles') # setting title of plot ax.set_title('cos') # set the tick marks for x axis ax.set_xticks([0,2,4,6]) # provide name to the x axis tick marks ax.set_xticklabels(['zero','two','four','six']) ax.set_yticks([-1,0,1]) plt.show()
Here is the output:
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.