Date Format and Convert Dates in Matplotlib plot_date

Recently, I was working on a data visualization project for a US-based retail company where I had to plot sales data over time using Python. Everything looked great, except the date format on the x-axis. The default date format in Matplotlib didn’t match the standard US format (MM/DD/YYYY), and I needed to fix it.

If you’ve ever faced the same issue, you’re not alone. Working with dates in Python can be tricky, especially when you need to control how they appear in your charts. That’s where Matplotlib’s plot_date() function comes in handy.

In this tutorial, I’ll show you how to change date format and convert dates in Matplotlib plot_date() function using Python. I’ll cover two easy methods for each, all based on my practical experience.

Understand Matplotlib’s plot_date() in Python

Before we move to formatting and conversion, let’s quickly understand what plot_date() does.

The plot_date() function in Matplotlib allows you to plot data points where the x-axis represents dates. It automatically handles date scaling and formatting, making it ideal for time-series visualization.

Here’s a simple example to get started:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime

# Sample data
dates = [datetime(2025, 1, 1), datetime(2025, 1, 2), datetime(2025, 1, 3)]
sales = [250, 300, 280]

# Plot using plot_date
plt.plot_date(dates, sales, linestyle='solid', color='blue')

plt.title("US Retail Sales Over Time")
plt.xlabel("Date")
plt.ylabel("Sales ($)")
plt.tight_layout()
plt.show()

This code plots a simple line chart showing daily sales. However, you might notice that the date format on the x-axis may not look how you want it, and that’s what we’ll fix next.

Change Date Format in Matplotlib plot_date (Python)

When you plot dates in Matplotlib, the default format might not match your region’s standard. In the US, we usually prefer MM/DD/YYYY, while Matplotlib might show YYYY-MM-DD or even abbreviated month names.

Method 1 – Use DateFormatter from matplotlib.dates

The easiest way to change the date format in Matplotlib’s plot_date() is by using the DateFormatter class. It lets you specify exactly how you want your dates to appear.

Let’s see how it works in Python.

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime

# Sample data
dates = [datetime(2025, 3, 1), datetime(2025, 3, 2), datetime(2025, 3, 3), datetime(2025, 3, 4)]
sales = [120, 150, 170, 160]

# Create the plot
plt.plot_date(dates, sales, linestyle='solid', color='green')

# Format the x-axis dates
date_format = mdates.DateFormatter('%m/%d/%Y')
plt.gca().xaxis.set_major_formatter(date_format)

plt.title("US Sales Trend (Custom Date Format)")
plt.xlabel("Date (MM/DD/YYYY)")
plt.ylabel("Sales ($)")
plt.gcf().autofmt_xdate()  # Auto-rotate date labels
plt.tight_layout()
plt.show()

I have executed the above example code and added the screenshot below.

Date Format in Matplotlib plot_date

In this example, I used %m/%d/%Y to display dates in the US format. The autofmt_xdate() method automatically rotates the labels, preventing overlap.

Method 2 – Use ConciseDateFormatter for Cleaner Axes

If you’re plotting longer time periods (like months or years), your x-axis can get cluttered. The ConciseDateFormatter provides a cleaner, more readable output.

Here’s how I use it.

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

# Generate sample data for 10 days
dates = [datetime(2025, 4, 1) + timedelta(days=i) for i in range(10)]
sales = [200 + i*10 for i in range(10)]

# Create the plot
plt.plot_date(dates, sales, linestyle='solid', color='purple')

# Use ConciseDateFormatter for a cleaner look
locator = mdates.AutoDateLocator()
formatter = mdates.ConciseDateFormatter(locator)

plt.gca().xaxis.set_major_locator(locator)
plt.gca().xaxis.set_major_formatter(formatter)

plt.title("US Sales Report (Concise Date Format)")
plt.xlabel("Date")
plt.ylabel("Sales ($)")
plt.tight_layout()
plt.show()

I have executed the above example code and added the screenshot below.

Matplotlib Date Format in plot_date

This method automatically adapts the date format based on the range of your data. It’s perfect for dashboards or reports where space is limited.

Date Conversion in Matplotlib plot_date (Python)

Sometimes, your data doesn’t come in a Python datetime format. Maybe your dataset uses strings like “2025-05-10” or timestamps like 1736428800. In that case, you’ll need to convert your dates before plotting.

Method 1 – Use Python’s datetime.strptime()

If your dates are in string format, Python’s built-in datetime.strptime() method is your best friend. It converts strings into datetime objects that Matplotlib can understand.

Here’s a simple example.

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime

# String-based dates (common in CSV files)
date_strings = ["03/01/2025", "03/02/2025", "03/03/2025", "03/04/2025"]
sales = [100, 120, 140, 130]

# Convert strings to datetime objects
dates = [datetime.strptime(d, "%m/%d/%Y") for d in date_strings]

# Plot the data
plt.plot_date(dates, sales, linestyle='solid', color='red')

plt.title("Converted Date Strings to Datetime (Python Example)")
plt.xlabel("Date")
plt.ylabel("Sales ($)")
plt.tight_layout()
plt.show()

I have executed the above example code and added the screenshot below.

Convert Dates in Matplotlib plot_date

This method is especially useful when importing data from Excel or CSV files. I use it often when cleaning datasets before analysis.

Method 2 – Use matplotlib.dates.num2date() in Python

Sometimes, your dataset may store dates as numeric timestamps (like UNIX time). Matplotlib can handle these too, but you’ll need to convert them to readable dates.

Here’s how I handle this in Python.

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime
import numpy as np

# Example UNIX timestamps
timestamps = [1735689600, 1735776000, 1735862400, 1735948800]  # Jan 1–4, 2025
sales = [220, 250, 270, 260]

# Convert UNIX timestamps to Matplotlib date format
dates = mdates.epoch2num(timestamps)

# Plot the data
plt.plot_date(dates, sales, linestyle='solid', color='orange')

# Format the dates for better readability
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%b %d, %Y'))

plt.title("Sales Data from UNIX Timestamps (Python Example)")
plt.xlabel("Date")
plt.ylabel("Sales ($)")
plt.tight_layout()
plt.show()

This approach is particularly useful when working with API data or logs where timestamps are common. The epoch2num() function converts UNIX timestamps into a format that Matplotlib can interpret as dates.

Pro Tip for Python Developers

Whenever you’re working with date formatting or conversion in Python, always check the type of your date data first. You can use:

print(type(dates[0]))

If it’s not a datetime.datetime, or a Matplotlib-compatible numeric date, you’ll need to convert it before plotting. This small check can save you hours of debugging!

So that’s how I handle date formatting and date conversion in Matplotlib’s plot_date() using Python.

  • Use DateFormatter or ConciseDateFormatter to control how your dates appear on the x-axis.
  • Convert date strings or timestamps using datetime.strptime() or mdates.epoch2num() before plotting.

These methods have helped me create clear, professional-looking time-series charts for clients across the US. With just a few lines of Python code, you can make your visualizations more readable and presentation-ready.

You may like to read other Matplotlib articles:

Leave a Comment

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.