Great question! When working with subplots in Matplotlib, you can control the tick marks for each subplot individually by accessing the corresponding Axes object. Here's how you can apply tick spacing (e.g., every other tick) to subplots using both methods mentioned earlier.
✅ Example: Set Tick Marks for Subplots
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
# Create some example data
x = range(20)
y1 = [i**2 for i in x]
y2 = [i**1.5 for i in x]
# Create subplots
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 6))
# Plot data
ax1.plot(x, y1)
ax2.plot(x, y2)
# Method 1: Use MultipleLocator to set ticks every 2 units
ax1.xaxis.set_major_locator(MultipleLocator(2))
ax2.xaxis.set_major_locator(MultipleLocator(2))
# Optional: Set y-axis ticks too
# ax1.yaxis.set_major_locator(MultipleLocator(50))
# ax2.yaxis.set_major_locator(MultipleLocator(10))
plt.tight_layout()
plt.show()
🔁 Alternatively: Manually set tick positions
If you want to manually specify tick positions (e.g., every other value in your x data):
# Set x-ticks manually for each subplot
ax1.set_xticks(x[::2])
ax2.set_xticks(x[::2])
📝 Notes
- If you're using
plt.subplots() with more than two subplots, you can loop through the axes:
fig, axes = plt.subplots(2, 2)
for ax in axes.flat:
ax.plot(x, y1)
ax.xaxis.set_major_locator(MultipleLocator(2))
- Use
MultipleLocator when you want consistent spacing regardless of the data range.
- Use
set_xticks() when you want full control over the exact tick positions.
Let me know if you need help with a specific subplot layout!