Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Centering x-tick labels between tick marks in Matplotlib
When creating time series plots in Matplotlib, you might want to center x-tick labels between tick marks rather than placing them directly on the ticks. This creates a cleaner look for date ranges or categorical data.
Understanding the Approach
To center labels between ticks, we use two sets of locators ?
- Major locator − Places the actual tick marks
- Minor locator − Places the labels between major ticks
- Formatters − Control what appears at each location
Example with Sample Data
Here's how to center month labels between tick marks using stock price data ?
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as dates
import matplotlib.ticker as ticker
from datetime import datetime, timedelta
# Create sample date and price data
start_date = datetime(2023, 1, 1)
date_range = [start_date + timedelta(days=x) for x in range(250)]
prices = 100 + np.cumsum(np.random.randn(250) * 0.5)
plt.rcParams["figure.figsize"] = [10, 4]
plt.rcParams["figure.autolayout"] = True
fig, ax = plt.subplots()
ax.plot(date_range, prices)
# Major ticks at month starts (invisible)
ax.xaxis.set_major_locator(dates.MonthLocator())
# Minor ticks at month midpoints (for labels)
ax.xaxis.set_minor_locator(dates.MonthLocator(bymonthday=15))
# Hide major tick labels, show minor tick labels
ax.xaxis.set_major_formatter(ticker.NullFormatter())
ax.xaxis.set_minor_formatter(dates.DateFormatter('%b'))
# Center the minor tick labels and hide tick lines
for tick in ax.xaxis.get_minor_ticks():
tick.tick1line.set_markersize(0)
tick.tick2line.set_markersize(0)
tick.label1.set_horizontalalignment('center')
ax.set_title('Stock Price with Centered Month Labels')
ax.set_ylabel('Price ($)')
plt.show()
Simpler Example with Categories
For categorical data, you can achieve the same effect more directly ?
import matplotlib.pyplot as plt
import numpy as np
# Sample data
categories = ['Q1', 'Q2', 'Q3', 'Q4']
values = [20, 35, 30, 25]
fig, ax = plt.subplots(figsize=(8, 5))
# Create bars
bars = ax.bar(range(len(categories)), values, width=0.8)
# Set ticks between bars
ax.set_xticks([i + 0.5 for i in range(len(categories) - 1)], minor=True)
ax.set_xticklabels(['', 'vs', 'vs', ''], minor=True)
# Set main category labels
ax.set_xticks(range(len(categories)))
ax.set_xticklabels(categories)
ax.set_title('Quarterly Sales with Centered Comparison Labels')
ax.set_ylabel('Sales (in thousands)')
plt.show()
Key Components
| Component | Purpose | Method |
|---|---|---|
| Major Locator | Position tick marks | set_major_locator() |
| Minor Locator | Position labels | set_minor_locator() |
| Formatters | Control label content | set_major_formatter() |
| Alignment | Center labels | set_horizontalalignment() |
Conclusion
Use major and minor locators with different formatters to center x-tick labels between tick marks. This technique works well for time series data and categorical plots where labels represent ranges rather than specific points.
Advertisements
