In this article, we will see how can we change the tick frequency on the x-axis or y-axis in the Matplotlib library. Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. If you had not installed the Matplotlib library you can install it using the pip command.
What is Python Tick Frequency?
It is the property that specifies the number of units between the tick marks in the track bar. In other words, this frequency is used to control the shrink or widened of your data points that are visualized across a graph.
Here, we will cover two ways to change the tick frequency of the x-axis or y-axis:
- matplotlib.pyplot.xticks()
- matplotlib.ticker.MultipleLocator()
Using matplotlib.pyplot.xticks() method
To change the tick frequency in the Matplotlib module we have xticks and yticks functions to change the frequency of ticks on the x-axis and y-axis respectively.
Syntax: matplotlib.pyplot.xticks(ticks=None, labels=None, *, minor=False, **kwargs)
Example
We imported the matplotlib.pyplot module as plt, NumPy as np, and then plotted a bar graph by using plt.plot() function for values of the x-axis we used the values of list x, and for the y-axis, we used the values of list y and set some labels to x-axis and y-axis by using the function xlabels() and ylabels(), and set the tick frequency by using xticks() function in which we pass arrange function of NumPy module which returns evenly spaced values within a given interval here it is 0 to 1000 with intervals of 100.
Python3
import matplotlib.pyplot as plt import numpy as np x = [ 20 , 70 , 105 , 220 , 385 , 590 , 859 ] y = [ 10 , 20 , 30 , 40 , 50 , 60 , 70 ] plt.plot(x, y) plt.xlabel( 'X-axis' ) plt.ylabel( 'Y-axis' ) plt.xticks(np.arange( 0 , 1000 , 100 )) plt.show() |
Output:
If we do not set the tick frequency it will take the default frequency in the below output we do not set the frequency it is on its default frequency.
matplotlib.ticker.MultipleLocator() Method
We have another method to set the tick frequency we set it by using matplotlib.ticker.MultipleLocator(). Let’s see the Implementation with the help of example
Example
We imported the matplotlib.pyplot module as plt, matplotlib.ticker module as ticker and then plotted a bar graph by using plt.plot() function for values of the x-axis we used the values of list x and for the y-axis, we used the values of list y and set the tick frequency by using xaxis.set_major_locator(ticker.MultipleLocator(space)) in which we pass space which is sets as 80 hence tick frequency of 80 is set on the x-axis
Python3
import matplotlib.pyplot as plt import matplotlib.ticker as ticker x = [ 20 , 70 , 105 , 220 , 385 , 590 , 859 ] y = [ 10 , 20 , 30 , 40 , 50 , 60 , 70 ] fig, ax = plt.subplots( 1 , 1 ) ax.plot(x, y) space = 80 ax.xaxis.set_major_locator(ticker.MultipleLocator(space)) plt.show() |
Output: