Python xticks in subplots

Subplots allow you to display multiple plots in a single figure by dividing it into a grid. When working with subplots, you can customize the x-axis ticks for each subplot independently using plt.xticks().

Understanding Subplot Layout

The plt.subplot() function creates subplots using three parameters: nrows, ncols, and index. For example, plt.subplot(121) creates a 1×2 grid and selects the first subplot.

Basic Subplot with Different X-ticks

Here's how to create two subplots with custom x-tick positions ?

import matplotlib.pyplot as plt

line1 = [21, 14, 81]
line2 = [31, 6, 12]

# First subplot - even x-ticks
plt.subplot(121)
plt.plot(line1, linestyle='dashed')
plt.margins(0.2)
plt.xticks([0, 2, 4, 6])
plt.title("X-ticks at even places")

# Second subplot - odd x-ticks  
plt.subplot(122)
plt.plot(line2)
plt.margins(0.2)
plt.xticks([1, 3, 5, 7])
plt.title("X-ticks at odd places")

plt.tight_layout()
plt.show()

Advanced Subplot Configuration

You can also use plt.subplots() to create multiple subplots with more control ?

import matplotlib.pyplot as plt
import numpy as np

# Create sample data
x = np.linspace(0, 10, 20)
y1 = np.sin(x)
y2 = np.cos(x)

# Create subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))

# First subplot
ax1.plot(x, y1, 'b-', linewidth=2)
ax1.set_xticks([0, 2, 4, 6, 8, 10])
ax1.set_title('Sine Wave - Custom X-ticks')
ax1.grid(True)

# Second subplot
ax2.plot(x, y2, 'r--', linewidth=2)
ax2.set_xticks([1, 3, 5, 7, 9])
ax2.set_title('Cosine Wave - Different X-ticks')
ax2.grid(True)

plt.tight_layout()
plt.show()

Key Parameters

Parameter Description Example
plt.subplot(nrows, ncols, index) Creates subplot in grid plt.subplot(1, 2, 1)
plt.xticks(ticks) Sets x-axis tick positions plt.xticks([0, 2, 4, 6])
plt.margins(x) Sets margin around data plt.margins(0.2)
plt.tight_layout() Adjusts spacing between subplots plt.tight_layout()

Conclusion

Using plt.xticks() in subplots allows you to customize x-axis tick positions independently for each subplot. Use plt.tight_layout() to prevent overlapping labels and ensure proper spacing between subplots.

Updated on: 2026-03-25T17:57:10+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements