How to sharex when using subplot2grid?

When using subplot2grid, you can share the x-axis between subplots by passing the sharex parameter. This creates linked subplots where zooming or panning one plot affects the other.

Steps to Share X-axis

  • Create random data using numpy

  • Create a figure using figure() method

  • Create the first subplot with subplot2grid()

  • Create the second subplot with sharex=ax1 parameter

  • Plot data on both subplots

  • Use tight_layout() to adjust spacing

  • Display the figure with show()

Example

Here's how to create subplots with shared x-axis using subplot2grid ?

import numpy as np
import matplotlib.pyplot as plt

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

# Create sample data
t = np.arange(0.0, 2.0, 0.01)
x = np.sin(2 * np.pi * t)
y1 = np.exp(-t)
y2 = x * y1

# Create figure
fig = plt.figure()

# Create first subplot
ax1 = plt.subplot2grid((4, 3), (0, 0), colspan=3, rowspan=2)

# Create second subplot with shared x-axis
ax2 = plt.subplot2grid((4, 3), (2, 0), colspan=3, sharex=ax1)

# Plot data
ax1.plot(t, y1, c='red', label='Exponential Decay')
ax2.plot(t, y2, c='orange', label='Modulated Signal')

# Add labels
ax1.set_ylabel('Amplitude')
ax2.set_ylabel('Amplitude')
ax2.set_xlabel('Time (s)')

# Adjust layout and display
plt.tight_layout()
plt.show()

How It Works

The sharex=ax1 parameter links the x-axis of the second subplot to the first subplot. When you zoom or pan on one plot, both plots will move together along the x-axis.

ax1 = subplot2grid((4,3), (0,0)) First subplot (reference) ax2 = subplot2grid((4,3), (2,0), sharex=ax1) Second subplot (shares x-axis)

Key Parameters

  • shape: Grid dimensions (rows, columns)

  • loc: Starting position (row, column)

  • colspan: Number of columns to span

  • rowspan: Number of rows to span

  • sharex: Reference subplot to share x-axis with

Conclusion

Use sharex=ax1 in subplot2grid to link x-axes between subplots. This creates synchronized zooming and panning behavior, making it easier to compare data across multiple plots.

Updated on: 2026-03-25T19:59:17+05:30

485 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements