How to use xticks() and yticks() In Python
xticks() and yticks() is the function that lets us customize the x ticks and y ticks by giving the values as a list, and we can also give labels for the ticks, matters, and as **kwargs we can apply text effects on the tick labels.
Syntax: matplotlib.pyplot.xticks(ticks=None, labels=None, **kwargs)
Parameter:
- ticks – The list of x ticks.
- labels – The list of tick labels
- kwargs – Text effects on labels
Returns:
- locs – The list of x ticks.
- labels – The list of tick text labels
Example:
In this example, we will use the ‘inline’ backend. Matplotlib graphs will be included in the notebook, next to the code. Then we give the x and y values to plot and take simple values because it would be easier to catch the concept. We are providing the title, x-label, y-label to show in the plot.
Python3
# Importing the libraries import pandas as pd import numpy as np from matplotlib import pyplot as plt # %matplotlib inline # Setting x and y values for the plot x = [ 1 , 2 , 3 , 4 ] y = [ 7 , 13 , 24 , 22 ] # Initiating the plot plt.plot(x, y) plt.title( "PLOT" ) # Setting the x and y labels plt.xlabel( "X-Axis" ) plt.ylabel( "Y-Axis" ) # Showing the plot plt.show() |
Output:
Now, we want only four ticks on both x and y-axis; we need to mention the ticks we need as a list with the xticks() and yticks() function. So In this code, we establish the same steps to plot. and then using xticks(), function we are mentioning the values(1,2,3,4) and by yticks() we are mentioning values (7,13,24,22). The same number of ticks is displayed in the output.
Python3
# Setting x and y values for the plot x = [ 1 , 2 , 3 , 4 ] y = [ 7 , 13 , 24 , 22 ] # Initiating the plot plt.plot(x, y) plt.title( "PLOT" ) # Setting the x and y labels plt.xlabel( "X-Axis" ) plt.ylabel( "Y-Axis" ) # Setting the number of ticks plt.xticks([ 1 , 2 , 3 , 4 ]) plt.yticks([ 7 , 13 , 24 , 22 ]) # Showing the plot plt.show() |
Output:
How to Change the Number of Ticks in Matplotlib?
In this article, we will see how to change the number of ticks on the plots in matplotlib in Python.
Contact Us