Date formatting helps show dates clearly on charts. It makes graphs easier to read and understand.
Date formatting with mdates in 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.
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))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.
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()
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.
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.
Practice
mdates.DateFormatter in matplotlib?Solution
Step 1: Understand the role of DateFormatter
mdates.DateFormatteris used to format date labels on axes in matplotlib plots.Step 2: Identify what DateFormatter customizes
It changes how dates are shown, for example, showing only month and day or full date and time.Final Answer:
To customize how dates appear on the x-axis of a plot -> Option AQuick Check:
DateFormatter formats dates = A [OK]
- Confusing DateFormatter with plot styling functions
- Thinking it changes plot colors
- Assuming it saves files
mdates.DateFormatter?Solution
Step 1: Recall strftime format codes
Year is '%Y', month is '%m', day is '%d' in strftime formatting.Step 2: Match correct format string
mdates.DateFormatter('%Y-%m-%d') uses '%Y-%m-%d' which correctly formats as Year-Month-Day.Final Answer:
mdates.DateFormatter('%Y-%m-%d') -> Option DQuick Check:
Correct strftime codes = B [OK]
- Omitting % signs in format string
- Using uppercase M for minutes instead of month
- Mixing order of year, month, day
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
dates = pd.date_range('2023-01-01', periods=3)
values = [10, 20, 15]
fig, ax = plt.subplots()
ax.plot(dates, values)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))
plt.show()Solution
Step 1: Understand the format string '%b %d'
'%b' is abbreviated month name (e.g., Jan), '%d' is day with leading zero.Step 2: Apply format to dates
Dates will appear as 'Jan 01', 'Jan 02', 'Jan 03' on x-axis labels.Final Answer:
Labels show dates as 'Jan 01', 'Jan 02', 'Jan 03' -> Option BQuick Check:
Format '%b %d' = 'Jan 01' style [OK]
- Confusing %b with %B (full month name)
- Expecting numeric month instead of abbreviated
- Ignoring leading zeros in day
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
dates = pd.date_range('2023-01-01', periods=3)
values = [5, 10, 15]
fig, ax = plt.subplots()
ax.plot(dates, values)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
ax.xaxis.set_major_locator(mdates.DayLocator())
plt.show()Solution
Step 1: Check imports and usage
All necessary imports are present, including mdates.DayLocator and DateFormatter.Step 2: Verify date formatting and locator
DateFormatter uses valid '%Y-%m-%d' format; DayLocator sets ticks daily. Dates are pandas datetime objects, which matplotlib handles.Final Answer:
No error; code runs and formats dates correctly -> Option AQuick Check:
Correct imports and usage = D [OK]
- Assuming pandas dates need manual conversion
- Using wrong format codes in DateFormatter
- Forgetting to set locator for ticks
mdates functions should you use to achieve this?Solution
Step 1: Choose locator for Mondays only
mdates.WeekdayLocator(byweekday=mdates.MO)selects ticks only on Mondays.Step 2: Format labels as 'Month-Day'
mdates.DateFormatter('%b-%d')formats dates like 'Jan-02'.Final Answer:
Use mdates.WeekdayLocator(byweekday=mdates.MO) and mdates.DateFormatter('%b-%d') -> Option CQuick Check:
Monday ticks + 'Jan-02' format = C [OK]
- Using DayLocator shows all days, not Mondays only
- MonthLocator shows monthly ticks, not weekly
- HourLocator is for time, not dates
Ready to prove it?
Pass the test and this pattern moves unknown
