Change the tick frequency on the x or y axis in Matplotlib – Python

In this tutorial, we will learn about how to change the tick frequency on the x or y axis in Matplotlib – Python.

You should know how to create a basic plot in Matplotlib. You can refer to the code below for this.

INPUT:

import matplotlib.pyplot as plt
x=[10,20,30,40,50,60,70,80]
y=[1,2,3,4,5,6,7,8]
plt.plot(x,y)

OUTPUT:

Change the tick frequency on the x or y axis in Matplotlib

To change the tick frequency:

For this purpose, we use plt.xticks(_the_list of_numbers_you_want_at_x _Axis_)

or plt.yticks(_the_list of_numbers_you_want_at_y _Axis_).

INPUT:

x=[10,20,30,40,50,60,70,80]
y=[1,2,3,4,5,6,7,8]
plt.plot(x,y)
plt.xticks([0,20,40,60,80])
plt.yticks([0,2,4,6,8])
plt.show()

OUTPUT:

plt.xticks()

A more convenient way :

We use python libraries to make our work easier and hence to allocate the x-axis ticks conveniently, we use the NumPy library.

We will use :

np.arange(_start_,_stop_,_interval_)

For example:

In the below code, the x-values are from 10 to 80 and we wish to create ticks at a regular interval of 6  starting from 0 and ending at the (_maximum_value_of_list_+1) from the list x. The stop value is excluded from this range. The default value of the interval is 1.

INPUT:

import numpy as np
x=[10,20,30,40,50,60,70,80]
y=[1,2,3,4,5,6,7,8]
plt.plot(x,y)
plt.xticks(np.arange(0,max(x)+1,6))
plt.yticks(np.arange(0,max(y)+1,1.5))
plt.show()

OUTPUT:

 

plt.xticks(np.arange(0,max(x)+1,6))

Leave a Reply

Your email address will not be published. Required fields are marked *