How to Change the Number of Ticks in Matplotlib

To change the number of ticks in Matplotlib, you can use the plt.xticks() and plt.yticks() methods. These methods take a list of values specifying where the ticks should go and can be used to customize the look of a plot. Additionally, you can use the plt.xlim() and plt.ylim() methods to set the limits of the plot. These methods take two values, the lower and upper limits, and will force the ticks to stay within those limits.


You can use the following syntax to change the number of ticks on each axis in Matplotlib:

#specify number of ticks on x-axis
plt.locator_params(axis='x', nbins=4)

#specify number of ticks on y-axis
plt.locator_params(axis='y', nbins=2) 

The nbins argument specifies how many ticks to display on each axis.

The following examples show how to use this syntax in practice.

Example 1: Specify Number of Ticks on Both Axes

The following code shows how to specify the number of ticks on both axes in a plot:

import matplotlib.pyplot as plt

#define data
x = [1, 2, 3, 4]
y = [7, 13, 24, 22]

#create plot
plt.plot(x, y, color='red')

#specify number of ticks on axes
plt.locator_params(axis='x', nbins=4)
plt.locator_params(axis='y', nbins=2)

Example 2: Specify Number of Ticks on X-Axis Only

The following code shows how to specify the number of ticks just on the x-axis:

import matplotlib.pyplot as plt

#define data
x = [1, 2, 3, 4]
y = [7, 13, 24, 22]

#create plot
plt.plot(x, y, color='red')

#specify number of ticks on x-axis
plt.locator_params(axis='x', nbins=2)

Example 3: Specify Number of Ticks on Y-Axis Only

The following code shows how to specify the number of ticks just on the y-axis:

import matplotlib.pyplot as plt

#define data
x = [1, 2, 3, 4]
y = [7, 13, 24, 22]

#create plot
plt.plot(x, y, color='red')

#specify number of ticks on y-axis
plt.locator_params(axis='y', nbins=2)

Change number of ticks in Matplotlib

x