How to Share Axis Between Subplots in Matplotlib
In matplotlib, you can share axes between subplots by using the
sharex and sharey parameters in plt.subplots(). Setting these to True or to an existing axis shares the respective axis, aligning ticks and labels across subplots.Syntax
The plt.subplots() function accepts sharex and sharey parameters to share axes between subplots.
sharex=True: Share the x-axis among subplots.sharey=True: Share the y-axis among subplots.- You can also pass an existing axis object to share axes selectively.
python
import matplotlib.pyplot as plt fig, axs = plt.subplots(nrows=2, ncols=1, sharex=True, sharey=False)
Example
This example creates two vertical subplots sharing the x-axis. The x-axis labels and ticks are aligned and shown only on the bottom subplot for clarity.
python
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.show()
Output
A figure window with two stacked plots: the top plot shows a sine wave, the bottom plot shows a cosine wave, and both share the same x-axis scale and ticks.
Common Pitfalls
Common mistakes when sharing axes include:
- Not setting
sharexorshareywhen creating subplots, leading to independent axes. - Trying to share axes after subplot creation, which is more complex.
- Forgetting that shared axes hide tick labels on all but the bottom or left subplot by default.
Always set sharing parameters during plt.subplots() call for best results.
python
import matplotlib.pyplot as plt # Wrong way: creating subplots separately fig = plt.figure() ax1 = fig.add_subplot(211) ax2 = fig.add_subplot(212) # Axes are not shared, x-axis ticks appear on both # Right way: share x-axis during creation fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
Quick Reference
| Parameter | Description | Values |
|---|---|---|
| sharex | Share x-axis among subplots | True, False, or axis object |
| sharey | Share y-axis among subplots | True, False, or axis object |
Key Takeaways
Use
sharex and sharey in plt.subplots() to share axes easily.Shared axes align ticks and labels, improving plot readability.
Set sharing parameters when creating subplots, not after.
Shared axes hide redundant tick labels on inner subplots by default.
You can share axes selectively by passing existing axis objects.