Complete the code to import the module needed to work with dates in matplotlib.
import matplotlib.pyplot as plt import matplotlib.dates as [1] fig, ax = plt.subplots()
The matplotlib.dates module is used to handle dates on the x-axis in matplotlib plots.
Complete the code to convert a list of date strings into datetime objects for plotting.
import datetime dates = ['2024-01-01', '2024-01-02', '2024-01-03'] dates_dt = [datetime.datetime.strptime(date, [1]) for date in dates]
The date strings are in the format 'year-month-day', so the format string "%Y-%m-%d" correctly parses them.
Fix the error in the code to plot dates on the x-axis correctly.
import matplotlib.pyplot as plt import matplotlib.dates as mdates import datetime dates = [datetime.datetime(2024, 1, 1), datetime.datetime(2024, 1, 2), datetime.datetime(2024, 1, 3)] values = [10, 20, 15] fig, ax = plt.subplots() ax.plot(dates, values) ax.xaxis.set_major_formatter([1]) plt.show()
The DateFormatter formats the dates on the x-axis as strings. Without it, dates may not display properly.
Fill both blanks to create a dictionary comprehension that maps each date string to its datetime object only if the date is after January 1, 2024.
import datetime dates = ['2023-12-31', '2024-01-01', '2024-01-02'] date_dict = {date: [1] for date in dates if [2]
strptime.The comprehension converts date strings to datetime objects only if the string date is greater than '2024-01-01'.
Fill all three blanks to create a plot with dates on the x-axis, format the dates as 'Month-Day', and rotate the labels for better readability.
import matplotlib.pyplot as plt import matplotlib.dates as mdates import datetime # Prepare data dates = [datetime.datetime(2024, 1, i) for i in range(1, 6)] values = [5, 7, 6, 8, 7] fig, ax = plt.subplots() ax.plot(dates, values) ax.xaxis.set_major_formatter([1]) plt.setp(ax.get_xticklabels(), rotation=[2], ha=[3]) plt.show()
The DateFormatter formats dates as 'Jan-01' etc. Rotating labels 45 degrees and aligning them right improves readability.