How to decrease the density of tick labels in subplots in Matplotlib?

When creating subplots in Matplotlib, tick labels can sometimes become too dense and cluttered. You can control the density of tick labels by adjusting the number of data points or using tick spacing parameters.

Understanding Tick Density

Tick density refers to how closely spaced the tick marks and labels are on your plot axes. Lower density means fewer, more spaced-out ticks for better readability.

Method 1: Using Density Parameter

Control tick density by limiting the number of data points used for tick positions ?

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [10.00, 6.00]
plt.rcParams["figure.autolayout"] = True

# Low density (fewer ticks)
density = 5
x = np.linspace(-2, 2, density)
y = np.sin(x)

plt.subplot(2, 1, 1)
plt.plot(x, y, 'b-o')
plt.xticks(x)
plt.title('Low Density (5 ticks)')

# High density (more ticks)
density = 15
x = np.linspace(-2, 2, density)
y = np.sin(x)

plt.subplot(2, 1, 2)
plt.plot(x, y, 'r-o')
plt.xticks(x)
plt.title('High Density (15 ticks)')

plt.tight_layout()
plt.show()

Method 2: Using MaxNLocator

Control the maximum number of ticks automatically with MaxNLocator ?

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator

plt.rcParams["figure.figsize"] = [10.00, 6.00]

x = np.linspace(0, 10, 100)
y = np.sin(x)

fig, (ax1, ax2) = plt.subplots(2, 1)

# Default ticks
ax1.plot(x, y)
ax1.set_title('Default Tick Density')

# Reduced tick density
ax2.plot(x, y)
ax2.xaxis.set_major_locator(MaxNLocator(nbins=6))
ax2.set_title('Reduced Tick Density (max 6 ticks)')

plt.tight_layout()
plt.show()

Method 3: Manual Tick Control

Set custom tick positions and labels for complete control ?

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 4*np.pi, 200)
y = np.sin(x)

plt.figure(figsize=[10, 4])
plt.plot(x, y)

# Set custom tick positions (every ?/2)
custom_ticks = np.arange(0, 4*np.pi + 0.1, np.pi/2)
custom_labels = ['0', '?/2', '?', '3?/2', '2?', '5?/2', '3?', '7?/2', '4?']

plt.xticks(custom_ticks, custom_labels)
plt.title('Custom Tick Positions and Labels')
plt.grid(True, alpha=0.3)
plt.show()

Comparison

Method Best For Flexibility
Density Parameter Simple plots with uniform spacing Low
MaxNLocator Automatic tick optimization Medium
Manual Control Custom tick positions and labels High

Conclusion

Use MaxNLocator for automatic tick density control, manual tick setting for custom positions, or adjust the density parameter for simple uniform spacing. Choose based on your specific plotting requirements.

Updated on: 2026-03-25T19:56:57+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements