Date formatting helps show dates clearly on charts. It makes graphs easier to read and understand.
0
0
Date formatting with mdates in Matplotlib
Introduction
You want to show time series data like stock prices or weather changes.
You need to customize how dates appear on the x-axis of a plot.
You want to display dates in a specific style, like 'Jan 2024' or '2024-01-01'.
You want to improve the look of date labels to avoid overlap or clutter.
Syntax
Matplotlib
import matplotlib.dates as mdates ax.xaxis.set_major_formatter(mdates.DateFormatter('format_string'))
Replace 'format_string' with the date format you want, like '%Y-%m-%d'.
This code sets how the major ticks on the x-axis show dates.
Examples
Shows dates as year-month-day, e.g., 2024-06-01.
Matplotlib
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))Shows dates as abbreviated month and day, e.g., Jun 01.
Matplotlib
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))Shows only the year, e.g., 2024.
Matplotlib
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))Sample Program
This code plots values over 5 days in June 2024. It formats the x-axis dates as 'Jun 01, 2024'. The dates are rotated to avoid overlap.
Matplotlib
import matplotlib.pyplot as plt import matplotlib.dates as mdates import datetime # Create some dates dates = [datetime.date(2024, 6, i) for i in range(1, 6)] values = [10, 15, 13, 17, 14] fig, ax = plt.subplots() ax.plot(dates, values) # Format the x-axis dates ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d, %Y')) # Rotate date labels for better readability plt.xticks(rotation=45) plt.title('Sample Date Formatting with mdates') plt.tight_layout() plt.show()
OutputSuccess
Important Notes
Use plt.xticks(rotation=45) to rotate date labels for clarity.
Common date format codes: %Y = year, %m = month number, %b = abbreviated month, %d = day.
Always import matplotlib.dates as mdates to access date formatters.
Summary
Date formatting makes time data easy to read on plots.
Use mdates.DateFormatter with a format string to set date style.
Rotate labels if they overlap for better visualization.