English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Matplotlib Tick Marks

Ticks are markers that represent data points on the axis. So far, Matplotlib has automatically taken over the task of interval points on the axis in all our previous examples. Matplotlib's default tick locators and formatters are usually sufficient in many common cases. It is possible to explicitly mention the position and label of the tick lines to meet specific requirements.

xticks() and yticks() functions take a list object as a parameter. The elements in the list represent the positions where the corresponding ticks will be displayed.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
ax.set_xticks([2,4,6,8,10])

This method will use tick marks to indicate data points at given positions. Similarly, corresponding to the tick lines, labels can be set separately by the set_xlabels() and set_ylabels() functions.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
ax.set_xlabels(['two', 'four', 'six', 'eight', 'ten'])

It will display text labels below the markers on the x-axis. The following example demonstrates the use of tick marks and labels.

Example code -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
#! /usr/bin/env python
 #coding=utf-8
 import matplotlib.pyplot as plt
 import numpy as np
 import math
 plt.rcParams['font.sans-serif'] = ['SimHei']  # Step one (replace sans-serif font)
 plt.rcParams['axes.unicode_minus'] = False  # Original text from [Lidi Huo], please contact the author for commercial use, retain the original link for non-commercial use:
 x = np.arange(0, math.pi)*2, 0.05)
 fig = plt.figure()
 ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes
 y = np.sin(x)
 ax.plot(x, y)
 ax.set_xlabel('Angle')
 ax.set_title('Sine')
 ax.set_xticks([0,2,4,6])
 ax.set_xticklabels(['zero','two','four','six'])
 ax.set_yticks([-1,0,1])
 plt.show()

Execute the above example code to get the following results -