Bird
Raised Fist0
Matplotlibdata~20 mins

Date formatting with mdates in Matplotlib - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Date Formatting Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the x-axis date format shown by this code?
This code plots dates on the x-axis using matplotlib and mdates. What date format will appear on the x-axis labels?
Matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime

dates = [datetime.datetime(2024, 1, i+1) for i in range(5)]
values = [10, 20, 15, 25, 30]

fig, ax = plt.subplots()
ax.plot(dates, values)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.show()
ADates formatted as 'DD-MM-YYYY', e.g., '01-01-2024'
BDates formatted as 'MM/DD/YYYY', e.g., '01/01/2024'
CDates formatted as 'Month day, Year', e.g., 'January 1, 2024'
DDates formatted as 'YYYY-MM-DD', e.g., '2024-01-01'
Attempts:
2 left
💡 Hint
Look at the string inside DateFormatter to see the date format pattern.
❓ data_output
intermediate
2:00remaining
How many major ticks appear on the x-axis?
Given this code that plots 10 daily dates and sets the major locator to mdates.DayLocator(interval=3), how many major ticks will appear on the x-axis?
Matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime

dates = [datetime.datetime(2024, 3, i+1) for i in range(10)]
values = range(10)

fig, ax = plt.subplots()
ax.plot(dates, values)
ax.xaxis.set_major_locator(mdates.DayLocator(interval=3))
plt.close(fig)  # Close plot to avoid display
A4
B3
C5
D10
Attempts:
2 left
💡 Hint
Count days from 1 to 10 with steps of 3: days 1,4,7,10.
🔧 Debug
advanced
2:00remaining
Why does this code raise a TypeError?
This code tries to format dates on the x-axis but raises a TypeError. What is the cause?
Matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime

dates = ['2024-01-01', '2024-01-02', '2024-01-03']
values = [1, 2, 3]

fig, ax = plt.subplots()
ax.plot(dates, values)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.show()
ADates are strings, but DateFormatter expects datetime objects, causing TypeError.
BThe DateFormatter format string '%Y-%m-%d' is invalid and causes TypeError.
CThe plot function cannot accept lists as x-axis values, causing TypeError.
DMissing plt.show() causes TypeError when rendering the plot.
Attempts:
2 left
💡 Hint
Check the type of the dates list elements.
❓ visualization
advanced
2:00remaining
Which option correctly sets monthly ticks with abbreviated month names?
You want the x-axis to show ticks at the start of each month with labels like 'Jan', 'Feb', etc. Which code snippet achieves this?
A
ax.xaxis.set_major_locator(mdates.WeekdayLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b'))
B
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b'))
C
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%B'))
D
ax.xaxis.set_major_locator(mdates.DayLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b'))
Attempts:
2 left
💡 Hint
Look for MonthLocator and '%b' for abbreviated month names.
🧠 Conceptual
expert
2:00remaining
What happens if you set both major and minor locators with mdates but only format major ticks?
If you set ax.xaxis.set_major_locator(mdates.MonthLocator()) and ax.xaxis.set_minor_locator(mdates.WeekdayLocator()), but only set a major formatter with DateFormatter, what will the minor ticks show?
AMinor ticks cause an error because they lack a formatter.
BMinor ticks show the same labels as major ticks, causing label overlap.
CMinor ticks appear without labels because no formatter is set for them.
DMinor ticks are hidden automatically if no formatter is set.
Attempts:
2 left
💡 Hint
Think about how matplotlib handles tick labels when no formatter is assigned.

Practice

(1/5)
1. What is the main purpose of using mdates.DateFormatter in matplotlib?
easy
A. To customize how dates appear on the x-axis of a plot
B. To change the color of the plot lines
C. To add grid lines to the plot
D. To save the plot as an image file

Solution

  1. Step 1: Understand the role of DateFormatter

    mdates.DateFormatter is used to format date labels on axes in matplotlib plots.
  2. Step 2: Identify what DateFormatter customizes

    It changes how dates are shown, for example, showing only month and day or full date and time.
  3. Final Answer:

    To customize how dates appear on the x-axis of a plot -> Option A
  4. Quick Check:

    DateFormatter formats dates = A [OK]
Hint: DateFormatter changes date label style on axes [OK]
Common Mistakes:
  • Confusing DateFormatter with plot styling functions
  • Thinking it changes plot colors
  • Assuming it saves files
2. Which of the following is the correct way to create a date formatter that shows dates as 'Year-Month-Day' using mdates.DateFormatter?
easy
A. mdates.DateFormatter('Y-m-d')
B. mdates.DateFormatter('%D-%M-%Y')
C. mdates.DateFormatter('%y/%M/%d')
D. mdates.DateFormatter('%Y-%m-%d')

Solution

  1. Step 1: Recall strftime format codes

    Year is '%Y', month is '%m', day is '%d' in strftime formatting.
  2. Step 2: Match correct format string

    mdates.DateFormatter('%Y-%m-%d') uses '%Y-%m-%d' which correctly formats as Year-Month-Day.
  3. Final Answer:

    mdates.DateFormatter('%Y-%m-%d') -> Option D
  4. Quick Check:

    Correct strftime codes = B [OK]
Hint: Use %Y, %m, %d for year, month, day in DateFormatter [OK]
Common Mistakes:
  • Omitting % signs in format string
  • Using uppercase M for minutes instead of month
  • Mixing order of year, month, day
3. What will be the output on the x-axis labels if the following code is used?
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()
medium
A. Labels show dates as '01-01-2023', '01-02-2023', '01-03-2023'
B. Labels show dates as 'Jan 01', 'Jan 02', 'Jan 03'
C. Labels show dates as '2023-01-01', '2023-01-02', '2023-01-03'
D. Labels show dates as '01 Jan', '02 Jan', '03 Jan'

Solution

  1. Step 1: Understand the format string '%b %d'

    '%b' is abbreviated month name (e.g., Jan), '%d' is day with leading zero.
  2. Step 2: Apply format to dates

    Dates will appear as 'Jan 01', 'Jan 02', 'Jan 03' on x-axis labels.
  3. Final Answer:

    Labels show dates as 'Jan 01', 'Jan 02', 'Jan 03' -> Option B
  4. Quick Check:

    Format '%b %d' = 'Jan 01' style [OK]
Hint: Check strftime codes to predict label format [OK]
Common Mistakes:
  • Confusing %b with %B (full month name)
  • Expecting numeric month instead of abbreviated
  • Ignoring leading zeros in day
4. Identify the error in this code snippet that tries to format dates on the x-axis:
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()
medium
A. No error; code runs and formats dates correctly
B. Missing import for DayLocator
C. DateFormatter format string is invalid
D. Plot will fail because dates are not converted to numbers

Solution

  1. Step 1: Check imports and usage

    All necessary imports are present, including mdates.DayLocator and DateFormatter.
  2. 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.
  3. Final Answer:

    No error; code runs and formats dates correctly -> Option A
  4. Quick Check:

    Correct imports and usage = D [OK]
Hint: Check imports and valid format strings first [OK]
Common Mistakes:
  • Assuming pandas dates need manual conversion
  • Using wrong format codes in DateFormatter
  • Forgetting to set locator for ticks
5. You want to plot daily sales data for a month and show x-axis labels only for Mondays in 'Month-Day' format (e.g., 'Jan-02'). Which combination of mdates functions should you use to achieve this?
hard
A. Use mdates.MonthLocator() and mdates.DateFormatter('%b')
B. Use mdates.DayLocator() and mdates.DateFormatter('%Y-%m-%d')
C. Use mdates.WeekdayLocator(byweekday=mdates.MO) and mdates.DateFormatter('%b-%d')
D. Use mdates.HourLocator() and mdates.DateFormatter('%H:%M')

Solution

  1. Step 1: Choose locator for Mondays only

    mdates.WeekdayLocator(byweekday=mdates.MO) selects ticks only on Mondays.
  2. Step 2: Format labels as 'Month-Day'

    mdates.DateFormatter('%b-%d') formats dates like 'Jan-02'.
  3. Final Answer:

    Use mdates.WeekdayLocator(byweekday=mdates.MO) and mdates.DateFormatter('%b-%d') -> Option C
  4. Quick Check:

    Monday ticks + 'Jan-02' format = C [OK]
Hint: Use WeekdayLocator with MO and DateFormatter '%b-%d' [OK]
Common Mistakes:
  • Using DayLocator shows all days, not Mondays only
  • MonthLocator shows monthly ticks, not weekly
  • HourLocator is for time, not dates
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard