0
0
Matplotlibdata~30 mins

Dates on x-axis in Matplotlib - Mini Project: Build & Apply

Choose your learning style9 modes available
Dates on x-axis
📖 Scenario: You work in a small bakery. You want to see how many cakes you sold each day last week. You have the dates and the number of cakes sold. You want to make a simple line chart with dates on the x-axis and cakes sold on the y-axis.
🎯 Goal: Create a line chart using matplotlib that shows the number of cakes sold each day last week. The x-axis should show the dates properly formatted.
📋 What You'll Learn
Create a list of dates for 7 days from 2024-04-01 to 2024-04-07
Create a list of integers for cakes sold each day
Use matplotlib to plot the dates on the x-axis and cakes sold on the y-axis
Format the x-axis to show dates clearly
💡 Why This Matters
🌍 Real World
Plotting dates on the x-axis is common in sales, weather, finance, and many other fields where data changes over time.
💼 Career
Data scientists and analysts often need to visualize time series data clearly to find trends and patterns.
Progress0 / 4 steps
1
Create the dates and sales data
Create a list called dates with these exact date strings: '2024-04-01', '2024-04-02', '2024-04-03', '2024-04-04', '2024-04-05', '2024-04-06', '2024-04-07'. Also create a list called cakes_sold with these exact numbers: 10, 15, 7, 12, 9, 14, 11.
Matplotlib
Need a hint?

Use a list for dates with the exact date strings. Use a list for cakes_sold with the exact numbers.

2
Convert date strings to datetime objects
Import datetime from datetime module. Create a new list called date_objects by converting each string in dates to a datetime object using datetime.strptime with format '%Y-%m-%d'.
Matplotlib
Need a hint?

Use a list comprehension to convert each date string to a datetime object.

3
Plot the data with dates on x-axis
Import matplotlib.pyplot as plt. Use plt.plot to plot date_objects on the x-axis and cakes_sold on the y-axis. Use plt.gcf().autofmt_xdate() to format the dates on the x-axis nicely.
Matplotlib
Need a hint?

Use plt.plot to draw the line. Use plt.gcf().autofmt_xdate() to rotate date labels.

4
Show the plot
Add a line to display the plot using plt.show().
Matplotlib
Need a hint?

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