0
0
Matplotlibdata~5 mins

Date formatting with mdates in Matplotlib - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of mdates in matplotlib?

mdates helps format and handle dates on plots, making it easier to display time-based data clearly.

Click to reveal answer
beginner
How do you set a date format for the x-axis using mdates?

You use mdates.DateFormatter with a format string like '%Y-%m-%d' and apply it with ax.xaxis.set_major_formatter().

Click to reveal answer
intermediate
What does mdates.AutoDateLocator() do?

It automatically chooses the best date ticks for the axis based on the data range, so the dates look neat and readable.

Click to reveal answer
beginner
Why is it important to use mdates for date plotting instead of plain numbers?

Dates are special data types. Using mdates ensures correct spacing, formatting, and interpretation of dates on plots.

Click to reveal answer
beginner
Show a simple code snippet to format dates on the x-axis with mdates.
<pre>import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime

dates = [datetime(2024, 1, i) for i in range(1, 6)]
values = [10, 15, 7, 12, 9]

fig, ax = plt.subplots()
ax.plot(dates, values)
ax.xaxis.set_major_locator(mdates.DayLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
fig.autofmt_xdate()  # Rotate date labels
plt.show()</pre>
Click to reveal answer
Which mdates class automatically picks date ticks based on data range?
ADateFormatter
BAutoDateLocator
CDayLocator
DDateConverter
What does DateFormatter('%Y-%m-%d') do?
AFormats dates as Year-Month-Day
BLocates dates on the axis
CConverts strings to dates
DRotates date labels
Which method applies the date format to the x-axis in matplotlib?
Aax.xaxis.set_major_formatter()
Bax.set_xlabel()
Cplt.date_format()
Dax.xaxis.set_major_locator()
Why use fig.autofmt_xdate() after setting date formats?
ATo add grid lines
BTo change the color of dates
CTo rotate date labels for better readability
DTo zoom into the date range
Which mdates locator would you use to show ticks every day?
AYearLocator
BMonthLocator
CAutoDateLocator
DDayLocator
Explain how to format dates on the x-axis of a matplotlib plot using mdates.
Think about importing mdates, setting locator and formatter, and rotating labels.
You got /5 concepts.
    Why is it better to use mdates for date plotting instead of plotting dates as strings or numbers?
    Consider how dates behave differently from plain numbers on a plot.
    You got /5 concepts.