How to set axis ticks in Matplotlib (With Examples)

Matplotlib provides a variety of methods to set the axis ticks on a plot. These methods include using the xticks() and yticks() functions to set the locations and labels of the ticks along the x-axis and y-axis respectively. Additionally, ticker.MultipleLocator() and ticker.FormatStrFormatter() can be used to set the intervals and formatting of the ticks. Examples of these methods are provided in the Matplotlib documentation.


You can use the following basic syntax to set the axis ticks in a Matplotlib plot:

#set x-axis ticks (step size=2)
plt.xticks(np.arange(min(x), max(x)+1, 2))

#set y-axis ticks (step size=5)
plt.yticks(np.arange(min(y), max(y)+1, 5))

The following example shows how to use this syntax in practice.

Example: Set Axis Ticks in Matplotlib

Suppose we use the following code to create a line plot in Matplotlib:

import numpy as np
import matplotlib.pyplot as plt

#define data
x = [0, 2, 7, 10, 12, 15, 18, 20]
y = [0, 5, 9, 13, 19, 22, 29, 36]

#create line plot
plt.plot(x,y)

#display line plot
plt.show()

By default, Matplotlib has chosen to use a step size of 2.5 on the x-axis and 5 on the y-axis.

We can use the following code to change the step size on each axis:

import numpy as np
import matplotlib.pyplot as plt

#define data
x = [0, 2, 7, 10, 12, 15, 18, 20]
y = [0, 5, 9, 13, 19, 22, 29, 36]

#create line plot
plt.plot(x,y)

#specify axis tick step sizes
plt.xticks(np.arange(min(x), max(x)+1, 2))
plt.yticks(np.arange(min(y), max(y)+1, 4))

#display line plot
plt.show()

Matplotlib set axis ticks

Notice that the step size on the x-axis is now 2 and the step size on the y-axis is 4.

The following tutorials explain how to fix other common errors in Python:

x