0
0
Matplotlibdata~5 mins

Major and minor ticks in Matplotlib

Choose your learning style9 modes available
Introduction

Major and minor ticks help you read graphs better by showing big and small marks on the axes.

When you want to show clear main points on a graph with major ticks.
When you want to add smaller marks between main points for detail with minor ticks.
When you want to customize how often ticks appear on your plot.
When you want to improve the look and readability of your charts.
When you want to control the spacing of labels on the axes.
Syntax
Matplotlib
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_minor_locator(locator)
ax.yaxis.set_major_locator(locator)
ax.yaxis.set_minor_locator(locator)

Use set_major_locator to control big ticks.

Use set_minor_locator to control small ticks between big ticks.

Examples
This example sets major ticks on the x-axis every 2 units and minor ticks every 0.5 units.
Matplotlib
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator

fig, ax = plt.subplots()
ax.plot([0, 10], [0, 100])

ax.xaxis.set_major_locator(MultipleLocator(2))  # Major ticks every 2 units
ax.xaxis.set_minor_locator(MultipleLocator(0.5))  # Minor ticks every 0.5 units

plt.show()
This example sets major ticks on the y-axis every 5 units and automatically adds 4 minor ticks between them.
Matplotlib
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator

fig, ax = plt.subplots()
ax.plot([0, 5], [0, 25])

ax.yaxis.set_major_locator(MultipleLocator(5))  # Major ticks every 5 units
ax.yaxis.set_minor_locator(AutoMinorLocator(4))  # 4 minor ticks between major ticks

plt.show()
Sample Program

This program plots a simple curve and sets major and minor ticks on both axes. It also shows grids for both major and minor ticks with different styles.

Matplotlib
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, AutoMinorLocator

fig, ax = plt.subplots()

# Plot some data
ax.plot([0, 1, 2, 3, 4, 5], [0, 1, 4, 9, 16, 25])

# Set major ticks on x-axis every 1 unit
ax.xaxis.set_major_locator(MultipleLocator(1))

# Set minor ticks on x-axis every 0.2 units
ax.xaxis.set_minor_locator(MultipleLocator(0.2))

# Set major ticks on y-axis every 5 units
ax.yaxis.set_major_locator(MultipleLocator(5))

# Set 4 minor ticks between major ticks on y-axis
ax.yaxis.set_minor_locator(AutoMinorLocator(4))

# Show grid for major and minor ticks
ax.grid(which='major', color='blue', linestyle='-')
ax.grid(which='minor', color='gray', linestyle=':')

plt.show()
OutputSuccess
Important Notes

Minor ticks do not have labels by default.

You can use different locator classes like MultipleLocator or AutoMinorLocator to control tick placement.

Adding grids for minor ticks can help see the smaller divisions clearly.

Summary

Major ticks mark main points on the axes.

Minor ticks mark smaller divisions between major ticks.

You can customize both using locator functions in matplotlib.