0
0
Matplotlibdata~5 mins

Dates on x-axis in Matplotlib

Choose your learning style9 modes available
Introduction

We use dates on the x-axis to show how data changes over time. It helps us see trends and patterns clearly.

Tracking daily sales over a month.
Showing temperature changes over a week.
Visualizing stock prices over several days.
Plotting website visitors by date.
Displaying progress of a project over time.
Syntax
Matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime

# Prepare dates and values
dates = [datetime(2024, 1, 1), datetime(2024, 1, 2), datetime(2024, 1, 3)]
values = [10, 15, 7]

# Plot data
plt.plot(dates, values)

# Format x-axis to show dates nicely
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())

plt.xlabel('Date')
plt.ylabel('Value')
plt.title('Values over Dates')
plt.gcf().autofmt_xdate()  # Rotate date labels
plt.show()

Use datetime objects for dates on x-axis.

mdates.DateFormatter controls how dates appear.

Examples
This example shows dates as 'Jun 01', 'Jun 02', etc., which is shorter and easier to read.
Matplotlib
from datetime import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

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

plt.plot(dates, values)
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))
plt.gcf().autofmt_xdate()
plt.show()
This example shows dates every 2 days on the x-axis for less clutter.
Matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime, timedelta

dates = [datetime(2024, 1, 1) + timedelta(days=i) for i in range(7)]
values = [3, 5, 2, 8, 7, 6, 4]

plt.plot(dates, values)
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=2))
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))
plt.gcf().autofmt_xdate()
plt.show()
Sample Program

This program plots daily temperatures over one week with dates on the x-axis formatted as 'YYYY-MM-DD'. The dates are rotated for easy reading.

Matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime, timedelta

# Create dates for one week
start_date = datetime(2024, 4, 1)
dates = [start_date + timedelta(days=i) for i in range(7)]

# Sample values for each date
values = [20, 22, 19, 24, 23, 25, 21]

# Plot the data
plt.plot(dates, values, marker='o')

# Format the x-axis to show dates nicely
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))

plt.xlabel('Date')
plt.ylabel('Temperature (Β°C)')
plt.title('Daily Temperatures Over One Week')
plt.gcf().autofmt_xdate()  # Rotate date labels for better fit
plt.tight_layout()
plt.show()
OutputSuccess
Important Notes

Always use datetime objects for dates, not strings, to avoid errors.

Use autofmt_xdate() to rotate date labels so they don’t overlap.

You can change the date format by modifying the string in DateFormatter, like '%b %d' for 'Jun 01'.

Summary

Dates on the x-axis help show how data changes over time.

Use datetime objects and matplotlib.dates to format dates.

Rotate date labels for better readability with autofmt_xdate().