0
0
Matplotlibdata~30 mins

Date formatting with mdates in Matplotlib - Mini Project: Build & Apply

Choose your learning style9 modes available
Date formatting with mdates
📖 Scenario: You are analyzing daily sales data for a small shop. You want to plot the sales over a week and show the dates nicely on the x-axis.
🎯 Goal: Create a line plot of sales over dates and format the x-axis dates using mdates for clear date labels.
📋 What You'll Learn
Create a list of dates for one week using datetime.date
Create a list of sales numbers matching the dates
Use matplotlib to plot sales vs dates
Use mdates to format the x-axis dates as 'Day-Month'
Display the plot with formatted date labels
💡 Why This Matters
🌍 Real World
Date formatting is important when visualizing time series data like sales, weather, or stock prices to make charts easy to read.
💼 Career
Data scientists and analysts often use date formatting to create clear and professional time-based visualizations for reports and presentations.
Progress0 / 4 steps
1
Create the dates and sales data
Create a list called dates with these exact datetime.date values: 2024-06-01, 2024-06-02, 2024-06-03, 2024-06-04, 2024-06-05, 2024-06-06, 2024-06-07. Also create a list called sales with these exact values: 150, 200, 170, 220, 180, 210, 190.
Matplotlib
Need a hint?

Use datetime.date(year, month, day) to create each date.

2
Set up the date formatter
Import matplotlib.pyplot as plt and matplotlib.dates as mdates. Create a variable called date_format that uses mdates.DateFormatter to format dates as '%d-%b' (day and abbreviated month).
Matplotlib
Need a hint?

Use mdates.DateFormatter('%d-%b') to create the formatter.

3
Plot the sales data with formatted dates
Use plt.plot to plot dates on the x-axis and sales on the y-axis. Then get the current axes with ax = plt.gca(). Use ax.xaxis.set_major_formatter(date_format) to apply the date formatter to the x-axis.
Matplotlib
Need a hint?

Use plt.plot(dates, sales) to plot, then ax = plt.gca() and ax.xaxis.set_major_formatter(date_format).

4
Display the plot
Write plt.show() to display the plot with the formatted date labels on the x-axis.
Matplotlib
Need a hint?

Use plt.show() to display the plot window.