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
Pandas timeseries plot setting X-axis major and minor ticks and labels
When working with Pandas time series data, you often need to customize the X-axis ticks and labels for better visualization. This involves setting both major and minor ticks to display dates at appropriate intervals.
Steps
Create a random number generator with a fixed seed for reproducible results.
Generate a fixed frequency DatetimeIndex using
pd.date_range()from '2020-01-01' to '2021-01-01'.Create sample data using a mathematical function or random distribution.
Build a DataFrame with the time series data.
Create a plot with custom figure size and configure major/minor ticks.
Display the plot using
plt.show().
Basic Time Series Plot
Let's start by creating a basic time series plot with Pandas ?
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
# Create random number generator
rng = np.random.default_rng(seed=1)
# Generate date range
date_day = pd.date_range(start='2020-01-01', end='2021-01-01', freq='D')
# Create sample data (exponential decay)
df_day = pd.DataFrame(dict(speed=[pow(2, -i/50) for i in range(len(date_day))]),
index=date_day)
# Create the plot
df_day.plot(figsize=(10, 5))
plt.title('Time Series Plot with Default Ticks')
plt.show()
Customizing Major and Minor Ticks
To have better control over the X-axis, we can set custom major and minor ticks using matplotlib's date formatting ?
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import matplotlib.dates as mdates
# Create data
rng = np.random.default_rng(seed=1)
date_day = pd.date_range(start='2020-01-01', end='2021-01-01', freq='D')
df_day = pd.DataFrame(dict(speed=[pow(2, -i/50) for i in range(len(date_day))]),
index=date_day)
# Create plot
fig, ax = plt.subplots(figsize=(10, 5))
df_day.plot(ax=ax)
# Set major ticks to show every 2 months
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=2))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
# Set minor ticks to show every month
ax.xaxis.set_minor_locator(mdates.MonthLocator())
# Rotate labels for better readability
plt.xticks(rotation=45)
plt.title('Time Series with Custom Major and Minor Ticks')
plt.tight_layout()
plt.show()
Advanced Tick Configuration
For more detailed control, you can customize both the frequency and format of ticks ?
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import matplotlib.dates as mdates
# Create sample data
date_day = pd.date_range(start='2020-01-01', end='2021-01-01', freq='D')
df_day = pd.DataFrame({
'speed': [pow(2, -i/50) for i in range(len(date_day))],
'acceleration': [np.sin(i/30) * 0.5 + 1 for i in range(len(date_day))]
}, index=date_day)
# Create subplot
fig, ax = plt.subplots(figsize=(12, 6))
df_day.plot(ax=ax)
# Configure major ticks (every 3 months)
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=3))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
# Configure minor ticks (every month)
ax.xaxis.set_minor_locator(mdates.MonthLocator())
# Customize grid
ax.grid(True, which='major', alpha=0.7)
ax.grid(True, which='minor', alpha=0.3)
# Format plot
plt.title('Multi-Series Time Plot with Custom Ticks and Grid')
plt.xlabel('Date')
plt.ylabel('Values')
plt.xticks(rotation=30)
plt.tight_layout()
plt.show()
Common Date Formatters
| Format Code | Output Example | Description |
|---|---|---|
%Y-%m-%d |
2020-01-15 | Full date format |
%b %Y |
Jan 2020 | Month abbreviation and year |
%m/%d |
01/15 | Month and day only |
%Y |
2020 | Year only |
Conclusion
Customizing X-axis ticks in Pandas time series plots involves using matplotlib's mdates module. Set major ticks with MonthLocator() or WeekdayLocator(), and format labels with DateFormatter() for optimal readability.
