Your dates came in as text, and your chart labels look wrong. Two small steps fix both.
In this tutorial, we’ll set a matplotlib date format and convert text, pandas and NumPy dates into values Matplotlib can plot.
Quick answer: Convert text with strptime() or pd.to_datetime(), plot it with ax.plot(), then attach a DateFormatter:
ax.xaxis.set_major_formatter(mdates.DateFormatter("%m/%d/%Y"))
We ran everything here on Matplotlib 3.11.2, pandas 3.0.6 and Python 3.12.5.
What You Need Before You Start
You need Python, Matplotlib and pandas. If the import fails, see how to install Matplotlib in Python first.
Step 1: Create the Sample Text Dates
Our running sample is 45 days of made-up Denver bakery sales. Save it as bakery_sales.py; the dates are US-style strings, just like a typical export.
import random
from datetime import date, timedelta
random.seed(2026)
start = date(2026, 3, 2)
raw_dates = [(start + timedelta(days=i)).strftime("%m/%d/%Y")
for i in range(45)]
sales = [round(1180 + i * 6 + random.gauss(0, 90), 2) for i in range(45)]
if __name__ == "__main__":
print(len(raw_dates), "days:", raw_dates[0], "to", raw_dates[-1])
print("First sale: $", sales[0], type(raw_dates[0]).__name__)
Output:
45 days: 03/02/2026 to 04/15/2026
First sale: $ 1257.93 str
Python still sees plain str values.
Step 2: Convert Text to Dates with strptime
Same sales, now with real dates. The pattern must match the text exactly:
from datetime import datetime
import matplotlib.pyplot as plt
from bakery_sales import raw_dates, sales
dates = [datetime.strptime(s, "%m/%d/%Y") for s in raw_dates]
print(dates[0], type(dates[0]).__name__)
fig, ax = plt.subplots(figsize=(7, 3.6), layout="constrained")
ax.plot(dates, sales)
ax.set_title("Denver bakery: daily sales, 2026")
ax.set_ylabel("Sales (USD)")
fig.autofmt_xdate()
print(type(ax.xaxis.get_major_locator()).__name__)
plt.show()
Output:
2026-03-02 00:00:00 datetime
AutoDateLocator

AutoDateLocator confirms Matplotlib built a date axis. The old plot_date() isn’t needed, as our plot_date replacement guide explains.
Step 3: Convert a Column with pandas to_datetime
For a column, pd.to_datetime() is shorter, and errors="coerce" turns bad rows into NaT instead of crashing:
import pandas as pd
from bakery_sales import raw_dates
dates = pd.to_datetime(pd.Series(raw_dates), format="%m/%d/%Y")
print(dates.dtype, "|", dates.iloc[0])
mixed = ["03/02/2026", "not a date"]
print(pd.to_datetime(mixed, format="%m/%d/%Y", errors="coerce"))
Output:
datetime64[us] | 2026-03-02 00:00:00
DatetimeIndex(['2026-03-02', 'NaT'], dtype='datetime64[us]', freq=None)
Need just part of the range afterward? Here’s how to set xlim with datetime values.
Step 4: Apply a US Date Format with DateFormatter
Same chart again, with one new line. DateFormatter takes the same codes as strftime():
from datetime import datetime
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
from bakery_sales import raw_dates, sales
dates = [datetime.strptime(s, "%m/%d/%Y") for s in raw_dates]
fig, ax = plt.subplots(figsize=(7, 3.6), layout="constrained")
ax.plot(dates, sales)
ax.set_ylabel("Sales (USD)")
ax.xaxis.set_major_formatter(mdates.DateFormatter("%m/%d/%Y"))
fig.autofmt_xdate()
plt.show()

Want different lines or colors? See line style and color on date charts.
Step 5: Shorten Labels with ConciseDateFormatter
ConciseDateFormatter repeats only what changes, so the labels stay flat:
from datetime import datetime
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
from bakery_sales import raw_dates, sales
dates = [datetime.strptime(s, "%m/%d/%Y") for s in raw_dates]
fig, ax = plt.subplots(figsize=(7, 3.6), layout="constrained")
ax.plot(dates, sales)
loc = mdates.AutoDateLocator()
ax.xaxis.set_major_locator(loc)
ax.xaxis.set_major_formatter(mdates.ConciseDateFormatter(loc))
plt.show()

To choose where ticks land, use our guide to date ticks and locators.
Step 6: Convert Dates to Numbers with date2num
Older code sometimes wants raw numbers. date2num() counts days since 1970, and num2date() reverses it:
from datetime import datetime
import matplotlib.dates as mdates
import numpy as np
day = datetime(2026, 3, 2, 12, 0)
num = float(mdates.date2num(day))
print("date2num: ", num)
back = mdates.num2date(num)
print("num2date: ", back)
print("US text: ", back.strftime("%m/%d/%Y"))
print("datetime64:", float(mdates.date2num(np.datetime64("2026-03-02"))))
Output:
date2num: 20514.5
num2date: 2026-03-02 12:00:00+00:00
US text: 03/02/2026
datetime64: 20514.0

Notice that num2date() returns a UTC-aware datetime.
Matplotlib Date Format Codes Cheat Sheet
| Code | 2:30 PM on March 2, 2026 |
|---|---|
%m/%d/%Y | 03/02/2026 |
%b %d, %Y | Mar 02, 2026 |
%B %Y | March 2026 |
%a %m/%d | Mon 03/02 |
%I:%M %p | 02:30 PM |
Common Mistakes with Matplotlib Dates
We reproduced all three in one script:
from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.axes import Axes
from bakery_sales import raw_dates, sales
fig, ax = plt.subplots()
ax.plot(raw_dates, sales)
print("Text x:", type(ax.xaxis.get_major_locator()).__name__)
try:
datetime.strptime("03/25/2026", "%d/%m/%Y")
except ValueError as err:
print("Swapped codes:", err)
print("Axes has plot_date:", hasattr(Axes, "plot_date"))
Output:
Text x: StrCategoryLocator
Swapped codes: time data '03/25/2026' does not match format '%d/%m/%Y'
Axes has plot_date: False

plot_date is gone.Text dates become categories, so DateFormatter can’t help. Day 25 can’t be a month, hence the ValueError. I’d always pass the format explicitly.
Why Does plot_date Raise an AttributeError?
Matplotlib 3.11 removed it. Use ax.plot(); for markers, see scatter and multi-line date charts.
Next Steps for Your Date Chart
Longer series? Our Matplotlib time series plot guide picks up from here.
Our team also put these together:
Frequently asked questions
How do I change the date format in Matplotlib?
Call ax.xaxis.set_major_formatter(mdates.DateFormatter("%m/%d/%Y")).
Why are my dates treated as categories?
They’re strings. Convert them with strptime() or pd.to_datetime().
Do I need date2num to plot dates?
No. ax.plot() accepts dates directly.
What does num2date return?
A timezone-aware datetime, in UTC by default.
How do I stop date labels overlapping?
Call fig.autofmt_xdate() or use ConciseDateFormatter.