Matplotlib - Ticks and Tick Labels



In the context of graphs and plotting, ticks are the small lines that show the scale of x and y-axes, providing a clear representation of the value associated with each tick. Whereas tick labels are the textual or numeric annotations associated with each tick on an axis, providing a clear representation of the value associated with each tick.

The following image represents the ticks and tick labels on a graph −

Input Image1

There are two types of ticks in a visualization: major and minor. Major tick marks are positions where labels can be placed, providing significant reference points. On the other hand, minor tick marks indicate values between the major ticks. See the below image for reference −

Input Image2

Ticks and Tick labels in Matplotlib

Matplotlib provides several tools for controlling ticks and tick labels on the axes, allowing you to customize ticks and tick labels by specifying custom positions and labels.

While the default behavior of Matplotlib is, automatically determines the number of ticks and their positions based on the range and scale of the data being plotted, this flexibility is useful for providing additional information or formatting the labels according to the preferences.

Basic Plot with Default Ticks and Lables

By default Matplotlib determines suitable tick positions and labels based on the provided data.

Example

This example generates a simple sine wave plot with default ticks and lables.

	import matplotlib.pyplot as plt
	import numpy as np

	# Sampel data
	t = np.linspace(0.0, 2.0, 201)
	s = np.sin(2 * np.pi * t)

	# Create plot
	fig, ax = plt.subplots(figsize=(7,4))

	# Plot the data
	plt.plot(t, s)
	plt.title('Sine Wave')
	plt.xlabel('X-axis')
	plt.ylabel('Y-axis')

	# Show the plot
	plt.show()

Output

On executing the above program you will get the following example −

Output Image1

Customizing Ticks and Tick Labels

Customizing ticks and tick labels can be achieved by using functions such as axes.set_xticks() and axes.set_yticks(), as well as plt.xticks() and plt.yticks().

Basic customization of ticks and tick labels may involve labeling ticks with customized strings, rotating custom tick labels, and few more.

Example

The following example demonstrates how to customize the x-axis ticks with specific positions, labels, and rotation. It converts or scales the axis values and redefine the tick frequency.

	import matplotlib.pyplot as plt
	import numpy as np

	# Create plot
	fig, ax = plt.subplots(figsize=(7,4))

	# Sample data
	x = np.linspace(0, 2 * np.pi, 100)
	y = np.sin(x)

	# Plotting the data
	plt.plot(x, y)
	plt.title('Sine Wave')
	plt.xlabel('X-axis')
	plt.ylabel('Y-axis')

	# Custom ticks and tick labels
	custom_ticks = [0, np.pi/2, np.pi, (3*np.pi)/2, 2*np.pi]
	custom_tick_labels = ['0', '$\pi/2$', '$\pi$', '3$\pi/2$', '2$\pi$']

	ax.set_xticks(custom_ticks, custom_tick_labels, rotation='vertical')

	# Display the plot
	plt.show()

Output

On executing the above program you will get the following example −

Output Image2

Example

This example demonstrates how to customize tick label positions and visibility, adjust separation between tick labels and axis labels, and turn off ticks and marks on a Matplotlib plot axis.

import numpy as np
import matplotlib.pyplot as plt

# Create subplots
fig, ax = plt.subplots(1, 1)

# Plot some data 
plt.plot([1, 2, 3, 4, 5])

# Set tick positions and labels
plt.xticks([1, 2, 3, 4, 5])

# show the tick labels on top of the plot?
ax.xaxis.set_tick_params(labeltop=True)

# set gap between the tick labels and axis labels 
plt.xlabel("X-axis", labelpad=25)

# turn off the ticks and marks on botton x axis
ax.tick_params(axis='both', which='both', bottom=False, top=True, left=True, right=False, labelbottom=True, labelleft=True)

# Displaying the plot
plt.show()

Output

On executing the above code you will get the following output −

Output Image3

Adding Minor Ticks

Minor ticks are initially disabled but can be enabled without labels by configuring the minor locator. The ticker module within the Matplotlib library provides two classes, namely MultipleLocator and AutoMinorLocator. These classes facilitate the placement of ticks at multiples of a specified base and allow you to specify a fixed number of minor intervals per major interval, respectively. As an alternative, the minorticks_on() method can be used to enable them.

Example

The following example demonstrates how to add the minor ticks to a plot. Here we will use the minorticks_on() method.

	import matplotlib.pyplot as plt
	import numpy as np
		
	# Sample data
	x = np.linspace(0, 2 * np.pi, 100)
	y = np.sin(x)

	fig, ax = plt.subplots(figsize=(7,4))

	# Plotting the data
	plt.plot(x, y)
	plt.title('Sine Wave')
	plt.xlabel('X-axis')
	plt.ylabel('Y-axis')

	# Adding minor ticks
	plt.minorticks_on()

	# Display the plot
	plt.show()	

Output

On executing the above program you will get the following example −

Output Image4
Advertisements