0
0
Matplotlibdata~10 mins

Date formatting with mdates in Matplotlib - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Date formatting with mdates
Import matplotlib and mdates
Create date data and values
Plot dates vs values
Set date formatter with mdates
Display formatted date ticks on x-axis
Show plot
This flow shows how to import mdates, create date data, plot it, apply date formatting, and display the plot with formatted dates.
Execution Sample
Matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime, timedelta

dates = [datetime.today() + timedelta(days=i) for i in range(5)]
values = [1, 3, 2, 5, 4]

plt.plot(dates, values)
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.gcf().autofmt_xdate()
plt.show()
This code plots values against dates and formats the x-axis dates as 'YYYY-MM-DD'.
Execution Table
StepActionVariable/FunctionResult/State
1Import matplotlib.pyplot as pltpltmatplotlib.pyplot module loaded
2Import matplotlib.dates as mdatesmdatesmatplotlib.dates module loaded
3Import datetime and timedeltadatetime, timedeltadatetime and timedelta classes loaded
4Create dates listdates[datetime objects for today + 0 to 4 days]
5Create values listvalues[1, 3, 2, 5, 4]
6Plot dates vs valuesplt.plotLine plot created with dates on x-axis
7Set major formatter for x-axisplt.gca().xaxis.set_major_formatterDates formatted as 'YYYY-MM-DD' on x-axis
8Show plotplt.showPlot window opens displaying formatted dates
9Exit-Plot displayed, execution ends
💡 Plot displayed and script ends after plt.show()
Variable Tracker
VariableStartAfter Step 4After Step 5Final
datesundefined[today, today+1d, today+2d, today+3d, today+4d][today, today+1d, today+2d, today+3d, today+4d][today, today+1d, today+2d, today+3d, today+4d]
valuesundefinedundefined[1, 3, 2, 5, 4][1, 3, 2, 5, 4]
Key Moments - 3 Insights
Why do we use plt.gca().xaxis.set_major_formatter instead of just plt.set_major_formatter?
Because plt.gca() gets the current axes object, and set_major_formatter is a method of the x-axis of that axes. plt itself does not have set_major_formatter.
What does '%Y-%m-%d' mean in DateFormatter?
It is a format string where %Y is 4-digit year, %m is 2-digit month, and %d is 2-digit day, so dates show like '2024-06-15'.
Why do dates appear on the x-axis instead of numbers?
Because matplotlib converts datetime objects to numbers internally but formats the ticks back to readable dates using the DateFormatter.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the state of 'dates' after Step 4?
AA list of integers from 0 to 4
BA list of datetime objects from today to 4 days later
CAn empty list
DA list of strings representing dates
💡 Hint
Check the 'dates' variable value in the 'After Step 4' column in variable_tracker.
At which step is the date format '%Y-%m-%d' applied to the x-axis?
AStep 5
BStep 6
CStep 7
DStep 8
💡 Hint
Look at the 'Action' column in execution_table for setting major formatter.
If we change the format string to '%b %d', how would the plot's x-axis labels change?
ADates would show as abbreviated month and day, e.g., 'Jun 15'
BDates would show as full year, e.g., '2024'
CDates would show as numeric day only, e.g., '15'
DDates would not change
💡 Hint
Refer to the explanation of '%Y-%m-%d' format in key_moments and how format strings control date display.
Concept Snapshot
Use matplotlib.dates (mdates) to format date ticks on plots.
Create datetime objects for x-axis data.
Plot dates vs values normally.
Use plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('format')) to set date format.
Common format: '%Y-%m-%d' for year-month-day.
Show plot with plt.show() to see formatted dates.
Full Transcript
This visual execution traces how to format dates on a matplotlib plot using mdates. First, we import matplotlib.pyplot as plt and matplotlib.dates as mdates, along with datetime and timedelta for date creation. We create a list of dates starting from today and increasing by one day for 5 days. We also create a list of values to plot. We plot the dates against values using plt.plot. Then, we set the x-axis major formatter to a DateFormatter with the format '%Y-%m-%d', which formats dates as year-month-day. Finally, we show the plot with plt.show(), which opens a window displaying the line plot with nicely formatted date labels on the x-axis. Variables 'dates' and 'values' hold the data, and the formatting is applied to the x-axis ticks. Key points include using plt.gca() to get the current axes and applying the formatter to the x-axis, understanding the date format string, and knowing that matplotlib internally converts dates to numbers but displays formatted dates. The quiz questions check understanding of variable states, step actions, and date format effects.