Set axes tick labels in matplotlib

matplolib_set_axes_tick_labels

Skill - Set axes ticks and tick labels in matplotlib

Table of Contents

Skills Required

Please make sure to have all the skills mentioned above to understand and execute the code mentioned below. Go through the above skills if necessary for reference or revision


Matplotlib is a plotting library tn the scipy ecosystem of libraries.

Please make sure that you covered thepost on basics


Sometimes we may desire to control the location of axis ticks of our subplots. This can be achieved by using the set_xticks and set_yticks functions of the axes handle.

Example - specify the position of axis ticks using set_xticks and set_yticks

import matplotlib.pyplot as plt
x = [0,1,2,3,4,5,6,7,8]
y = [8,6,4,2,9,7,6,3,1]

# create a plotting area and get the figure, axes handle in return
fig, ax = plt.subplots()

# plot data on the axes handle
ax.plot(x, y)

# specify the position of x axis ticks
ax.set_xticks([0,2,4,6,8])

# specify the position of y axis ticks
ax.set_yticks([0,3,6,9])

# print the plot
plt.show()

matlpotlib_axis_ticks_demo**

In order to use custom tick labels instead of default tick labels, we can use set_xticklabels and set_yticklabels functions of the axes handle

Example - specify the axis labels using set_xticklabels and set_yticklabels

import matplotlib.pyplot as plt
x = [0,1,2,3,4,5,6,7,8]
y = [8,6,4,2,9,7,6,3,1]

# create a plotting area and get the figure, axes handle in return
fig, ax = plt.subplots()

# plot data on the axes handle
ax.plot(x, y)

# specify the position of x axis ticks
ax.set_xticks([0,2,4,6,8])

# specify the tick labels of x axis
ax.set_xticklabels(['zero','two','four','six','eight'])

# specify the position of y axis ticks
ax.set_yticks([0,3,6,9])

# print the plot
plt.show()

matlpotlib_axis_tick_labels_demo

Example - avoid axis ticks by specifying empty array

import matplotlib.pyplot as plt
x = [0,1,2,3,4,5,6,7,8]
y = [8,6,4,2,9,7,6,3,1]

# create a plotting area and get the figure, axes handle in return
fig, ax = plt.subplots()

# plot data on the axes handle
ax.plot(x, y)

# provide empty array to specify that x axis ticks not required
ax.set_xticks([])

# print the plot
plt.show()

matlpotlib_blank_axis_tick_labels_demo

Video

You can the video on this post here


Online Interpreter

Although we recommend to practice the above examples in Visual Studio Code, you can run these examples online at https://pynative.com/online-python-code-editor-to-execute-python-code/

References


Table of Contents

Comments