Matplotlib – How to set xticks and yticks with imshow plot?

When working with imshow() plots in Matplotlib, you often need to customize the tick positions and labels on both axes. The set_xticks() and set_yticks() methods allow you to control exactly where ticks appear on your image plot.

Basic Example with Custom Tick Positions

Here's how to set custom tick positions for an imshow plot ?

import numpy as np
import matplotlib.pyplot as plt

# Set figure size
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

# Get current axis
ax = plt.gca()

# Create random dataset
data = np.random.rand(6, 6)

# Display data as image
ax.imshow(data)

# Set custom xticks and yticks
ax.set_xticks([1, 2, 3, 4, 5])
ax.set_yticks([1, 2, 3, 4, 5])

plt.show()

Setting Tick Labels

You can also customize the labels that appear at each tick position ?

import numpy as np
import matplotlib.pyplot as plt

# Create sample data
data = np.random.rand(5, 5)

# Create plot
fig, ax = plt.subplots(figsize=(6, 5))
im = ax.imshow(data, cmap='viridis')

# Set tick positions and labels
x_positions = [0, 1, 2, 3, 4]
y_positions = [0, 1, 2, 3, 4]
x_labels = ['A', 'B', 'C', 'D', 'E']
y_labels = ['Row1', 'Row2', 'Row3', 'Row4', 'Row5']

ax.set_xticks(x_positions)
ax.set_yticks(y_positions)
ax.set_xticklabels(x_labels)
ax.set_yticklabels(y_labels)

plt.show()

Advanced Tick Configuration

For more control, you can specify tick positions with rotation and styling ?

import numpy as np
import matplotlib.pyplot as plt

# Create heatmap data
data = np.random.rand(8, 6)

fig, ax = plt.subplots(figsize=(8, 6))
im = ax.imshow(data, cmap='coolwarm', aspect='auto')

# Set major ticks
ax.set_xticks(np.arange(0, 6, 1))
ax.set_yticks(np.arange(0, 8, 1))

# Set tick labels with rotation
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
categories = ['Cat1', 'Cat2', 'Cat3', 'Cat4', 'Cat5', 'Cat6', 'Cat7', 'Cat8']

ax.set_xticklabels(months, rotation=45)
ax.set_yticklabels(categories)

# Add minor ticks
ax.set_xticks(np.arange(-0.5, 6, 1), minor=True)
ax.set_yticks(np.arange(-0.5, 8, 1), minor=True)

plt.tight_layout()
plt.show()

Key Methods

Method Purpose Example
set_xticks() Set x-axis tick positions ax.set_xticks([0, 2, 4])
set_yticks() Set y-axis tick positions ax.set_yticks([1, 3, 5])
set_xticklabels() Set x-axis tick labels ax.set_xticklabels(['A', 'B', 'C'])
set_yticklabels() Set y-axis tick labels ax.set_yticklabels(['X', 'Y', 'Z'])

Conclusion

Use set_xticks() and set_yticks() to control tick positions on imshow plots. Combine with set_xticklabels() and set_yticklabels() for custom labels. This is essential for creating readable heatmaps and image plots.

Updated on: 2026-03-26T02:34:56+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements