0
0
Matplotlibdata~30 mins

Date locators for tick spacing in Matplotlib - Mini Project: Build & Apply

Choose your learning style9 modes available
Date locators for tick spacing
📖 Scenario: You are analyzing daily sales data for a small shop over one month. You want to create a line chart showing sales over time. To make the chart easy to read, you will set the spacing of date ticks on the x-axis using date locators.
🎯 Goal: Create a line plot of sales over dates and use matplotlib.dates date locators to set the tick spacing on the x-axis to show every 7 days.
📋 What You'll Learn
Create a list of dates for 30 days starting from 2024-01-01
Create a list of sales numbers for each date
Use matplotlib.dates DayLocator with interval 7 to set tick spacing
Plot the sales data with dates on the x-axis
Display the plot with properly spaced date ticks
💡 Why This Matters
🌍 Real World
Date locators help make time series charts easier to read by controlling how often dates appear on the axis. This is useful in sales, weather, finance, and many other fields.
💼 Career
Data scientists and analysts often visualize time series data. Knowing how to set date tick spacing improves the clarity and professionalism of reports and dashboards.
Progress0 / 4 steps
1
Create the sales data and dates
Create a list called dates with 30 consecutive dates starting from datetime.date(2024, 1, 1). Create a list called sales with these exact values: [20, 22, 19, 24, 30, 28, 25, 27, 29, 31, 33, 35, 34, 32, 30, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14].
Matplotlib
Need a hint?

Use a list comprehension with datetime.timedelta(days=i) to create consecutive dates.

2
Import date locator for tick spacing
Import matplotlib.pyplot as plt and import DayLocator from matplotlib.dates.
Matplotlib
Need a hint?

Use import matplotlib.pyplot as plt and from matplotlib.dates import DayLocator.

3
Set the date locator for tick spacing
Create a variable called locator and set it to DayLocator(interval=7). Then create a plot with plt.plot(dates, sales). Use plt.gca().xaxis.set_major_locator(locator) to set the x-axis major ticks to every 7 days.
Matplotlib
Need a hint?

Use DayLocator(interval=7) to show ticks every 7 days.

4
Display the plot
Add plt.show() to display the plot with date ticks spaced every 7 days.
Matplotlib
Need a hint?

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