0
0
Matplotlibdata~5 mins

Shared axes between subplots in Matplotlib

Choose your learning style9 modes available
Introduction

Sharing axes between subplots helps compare data easily by using the same scale. It keeps the charts aligned and neat.

When you want to compare trends across multiple charts with the same scale.
When you want to save space by not repeating axis labels on every subplot.
When you want to keep the layout clean and easy to read.
When you have multiple plots showing related data and want consistent zoom or pan.
When you want to highlight differences or similarities clearly between plots.
Syntax
Matplotlib
fig, axs = plt.subplots(nrows, ncols, sharex=True, sharey=True)

# sharex=True shares the x-axis
# sharey=True shares the y-axis

Use sharex=True to share the x-axis among subplots.

Use sharey=True to share the y-axis among subplots.

Examples
Both subplots will have the same x-axis scale and labels.
Matplotlib
fig, axs = plt.subplots(2, 1, sharex=True)
# Two rows, one column, x-axis shared
Both subplots will have the same y-axis scale and labels.
Matplotlib
fig, axs = plt.subplots(1, 2, sharey=True)
# One row, two columns, y-axis shared
More control: x-axis shared only in columns, y-axis shared only in rows.
Matplotlib
fig, axs = plt.subplots(2, 2, sharex='col', sharey='row')
# Share x-axis within columns and y-axis within rows
Sample Program

This code creates two stacked plots sharing the same x-axis. The x-axis labels appear only on the bottom plot, making the figure cleaner.

Matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

fig, axs = plt.subplots(2, 1, sharex=True)

axs[0].plot(x, y1)
axs[0].set_title('Sine Wave')

axs[1].plot(x, y2)
axs[1].set_title('Cosine Wave')

plt.xlabel('X axis')
plt.show()
OutputSuccess
Important Notes

Sharing axes helps keep plots aligned and easier to compare.

When axes are shared, only the outer plots show axis labels by default.

You can share axes partially using sharex='col' or sharey='row'.

Summary

Shared axes keep scales consistent across subplots.

Use sharex and sharey in plt.subplots() to share axes.

Shared axes improve readability and save space.