Bird
Raised Fist0
Matplotlibdata~20 mins

Dates on x-axis in Matplotlib - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Date Axis Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this matplotlib date plot code?
Consider the following Python code that plots dates on the x-axis using matplotlib. What will be the format of the x-axis labels shown in the plot?
Matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime

dates = [datetime(2024, 1, 1), datetime(2024, 1, 2), datetime(2024, 1, 3)]
values = [10, 20, 15]

fig, ax = plt.subplots()
ax.plot(dates, values)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.show()
ADates formatted as 'YYYY-MM-DD', e.g., '2024-01-01', '2024-01-02', '2024-01-03'
BDates formatted as 'MM/DD/YYYY', e.g., '01/01/2024', '01/02/2024', '01/03/2024'
CDates formatted as 'Day Month Year', e.g., '1 Jan 2024', '2 Jan 2024', '3 Jan 2024'
DDates shown as integers representing days since 1970-01-01
Attempts:
2 left
💡 Hint
Look at the format string passed to DateFormatter.
❓ data_output
intermediate
2:00remaining
How many major ticks appear on the x-axis?
Given this code that plots data with dates on the x-axis, how many major ticks will appear on the x-axis?
Matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime

dates = [datetime(2024, 5, 1), datetime(2024, 5, 2), datetime(2024, 5, 3), datetime(2024, 5, 4), datetime(2024, 5, 5)]
values = [5, 3, 6, 2, 7]

fig, ax = plt.subplots()
ax.plot(dates, values)
ax.xaxis.set_major_locator(mdates.DayLocator(interval=2))
plt.show()
A3 major ticks
B5 major ticks
C2 major ticks
D1 major tick
Attempts:
2 left
💡 Hint
Check the interval set in DayLocator and the date range.
❓ visualization
advanced
2:30remaining
Which plot shows correctly formatted monthly ticks on the x-axis?
You want to plot data with monthly ticks labeled as abbreviated month names (e.g., Jan, Feb). Which code snippet produces this correctly formatted x-axis?
A
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
B
ax.xaxis.set_major_locator(mdates.WeekdayLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b'))
C
ax.xaxis.set_major_locator(mdates.DayLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b'))
D
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b'))
Attempts:
2 left
💡 Hint
MonthLocator controls tick positions by month, DateFormatter controls label format.
🔧 Debug
advanced
2:00remaining
What error does this code raise when plotting dates?
This code attempts to plot dates on the x-axis but raises an error. What is the error type?
Matplotlib
import matplotlib.pyplot as plt
from datetime import datetime

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

plt.plot(dates, values)
plt.show()
ATypeError: float() argument must be a string or a number, not 'datetime.date'
BNo error, plot displays correctly
CValueError: could not convert string to float: '2024-01-01'
DAttributeError: 'str' object has no attribute 'toordinal'
Attempts:
2 left
💡 Hint
Matplotlib expects datetime objects or numbers, not date strings.
🚀 Application
expert
3:00remaining
What is the value of 'num_ticks' after running this code?
This code sets up a plot with dates on the x-axis and custom tick intervals. What is the number of major ticks on the x-axis after running?
Matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime

start = datetime(2024, 1, 1)
end = datetime(2024, 3, 1)

fig, ax = plt.subplots()
ax.set_xlim(start, end)
ax.xaxis.set_major_locator(mdates.MonthLocator(bymonthday=15))

# Count major ticks
num_ticks = len(ax.get_xticks())
plt.close(fig)
A1
B2
C3
D0
Attempts:
2 left
💡 Hint
MonthLocator with bymonthday=15 places ticks on the 15th of each month within limits.

Practice

(1/5)
1. What is the main reason to use datetime objects on the x-axis in matplotlib plots?
easy
A. To display dates properly and allow date-specific formatting
B. To speed up the plotting process
C. To change the color of the plot lines
D. To add grid lines automatically

Solution

  1. Step 1: Understand the role of datetime objects

    Datetime objects represent dates and times in Python, allowing matplotlib to recognize and format them correctly on the x-axis.
  2. Step 2: Identify the benefit for plotting

    Using datetime objects enables proper date formatting, such as showing months, days, or years, and helps in handling date ticks automatically.
  3. Final Answer:

    To display dates properly and allow date-specific formatting -> Option A
  4. Quick Check:

    Datetime objects = Proper date display [OK]
Hint: Use datetime objects to get correct date formatting on x-axis [OK]
Common Mistakes:
  • Using strings instead of datetime objects for dates
  • Expecting automatic color changes from datetime
  • Confusing grid lines with date formatting
2. Which of the following is the correct way to import the module used for date formatting in matplotlib?
easy
A. import matplotlib.date as mdate
B. import matplotlib.dates as mdates
C. import matplotlib.datetime as mdates
D. import matplotlib.dateformatter as mdates

Solution

  1. Step 1: Recall the correct module name

    The correct module for date formatting in matplotlib is called dates, not date or datetime.
  2. Step 2: Match the import alias

    Common practice is to import it as mdates for convenience.
  3. Final Answer:

    import matplotlib.dates as mdates -> Option B
  4. Quick Check:

    matplotlib.dates = mdates [OK]
Hint: Remember: 'dates' plural, alias 'mdates' [OK]
Common Mistakes:
  • Using singular 'date' instead of 'dates'
  • Confusing datetime module with matplotlib.dates
  • Using wrong alias causing import errors
3. What will the following code output?
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime

dates = [datetime(2024, 1, 1), datetime(2024, 1, 2), datetime(2024, 1, 3)]
values = [10, 20, 15]

plt.plot(dates, values)
plt.gcf().autofmt_xdate()
plt.show()
medium
A. A line plot with dates on x-axis formatted and rotated for readability
B. A line plot with numeric x-axis values instead of dates
C. An error because dates are not converted to strings
D. A scatter plot with dates on y-axis

Solution

  1. Step 1: Understand the plot function with datetime

    The plt.plot function accepts datetime objects on the x-axis and plots the corresponding values.
  2. Step 2: Effect of autofmt_xdate()

    This function rotates and formats the date labels on the x-axis to prevent overlap and improve readability.
  3. Final Answer:

    A line plot with dates on x-axis formatted and rotated for readability -> Option A
  4. Quick Check:

    autofmt_xdate() rotates date labels [OK]
Hint: Use autofmt_xdate() to rotate date labels automatically [OK]
Common Mistakes:
  • Expecting string conversion of dates automatically
  • Confusing plot type with scatter
  • Ignoring the effect of autofmt_xdate()
4. Identify the error in this code snippet that tries to plot dates on the x-axis:
import matplotlib.pyplot as plt
from datetime import datetime

dates = ['2024-01-01', '2024-01-02', '2024-01-03']
values = [5, 10, 15]

plt.plot(dates, values)
plt.show()
medium
A. plt.plot cannot plot lists
B. Values list length does not match dates list length
C. Missing import for matplotlib.dates module
D. Dates are strings, not datetime objects, causing incorrect x-axis formatting

Solution

  1. Step 1: Check the type of dates list

    The dates are given as strings, which matplotlib does not automatically convert to dates for axis formatting.
  2. Step 2: Understand the impact on plotting

    Using strings causes matplotlib to treat them as categorical labels, not dates, so date formatting and scaling won't work properly.
  3. Final Answer:

    Dates are strings, not datetime objects, causing incorrect x-axis formatting -> Option D
  4. Quick Check:

    Use datetime objects, not strings for dates [OK]
Hint: Convert date strings to datetime objects before plotting [OK]
Common Mistakes:
  • Using strings directly for dates
  • Assuming matplotlib auto-converts strings to dates
  • Ignoring the need for datetime conversion
5. You want to plot daily sales data for January 2024 with dates on the x-axis. You have a list of date strings and sales numbers. Which code snippet correctly converts the dates and formats the x-axis for clear display?
dates = ['2024-01-01', '2024-01-02', '2024-01-03']
sales = [100, 150, 120]
hard
A. from datetime import datetime plt.plot([datetime(d) for d in dates], sales) plt.show()
B. import matplotlib.pyplot as plt plt.plot(dates, sales) plt.xticks(rotation=45) plt.show()
C. from datetime import datetime import matplotlib.pyplot as plt import matplotlib.dates as mdates converted_dates = [datetime.strptime(d, '%Y-%m-%d') for d in dates] plt.plot(converted_dates, sales) plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%b %d')) plt.gcf().autofmt_xdate() plt.show()
D. import matplotlib.dates as mdates plt.plot(dates, sales) plt.gca().xaxis.set_major_locator(mdates.DayLocator()) plt.show()

Solution

  1. Step 1: Convert date strings to datetime objects

    Use datetime.strptime with the correct format to convert each string to a datetime object.
  2. Step 2: Format x-axis dates and rotate labels

    Use mdates.DateFormatter to set a readable date format and autofmt_xdate() to rotate labels for clarity.
  3. Final Answer:

    The code snippet that correctly converts dates and formats x-axis -> Option C
  4. Quick Check:

    Convert dates + format + rotate labels = from datetime import datetime import matplotlib.pyplot as plt import matplotlib.dates as mdates converted_dates = [datetime.strptime(d, '%Y-%m-%d') for d in dates] plt.plot(converted_dates, sales) plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%b %d')) plt.gcf().autofmt_xdate() plt.show() [OK]
Hint: Convert strings with strptime, format with DateFormatter, rotate labels [OK]
Common Mistakes:
  • Plotting strings without conversion
  • Using datetime(d) instead of strptime
  • Forgetting to rotate date labels
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