Create Time Series Plots Using Matplotlib in Python

As an experienced Python developer, I’ve worked with data visualization extensively. One of the most common visualization types I use is the time series plot. Matplotlib is the go-to library for creating these plots in Python. It’s flexible, powerful, and integrates well with other libraries like pandas.

In this article, I’ll walk you through practical methods to create time series plots using Matplotlib. I’ll also share tips from my own experience to help you avoid common issues.

Let’s get right in!

What is a Time Series Plot?

A time series plot is a graph that displays data points at successive time intervals. It’s widely used in finance, economics, weather forecasting, and many other fields. For example, if you want to visualize the daily closing prices of the S&P 500 index over the past year, a time series plot is your best friend.

Check out Matplotlib plot_date

Prepare Your Data for Time Series Plotting

Before plotting, your data needs to be in the right format. Typically, you’ll want a pandas DataFrame with a datetime index or a column containing datetime objects.

Here’s a quick example using US unemployment rates from the Bureau of Labor Statistics:

import pandas as pd

# Sample data: Monthly US unemployment rates for 2023
data = {
    'Date': pd.date_range(start='2023-01-01', periods=6, freq='M'),
    'Unemployment_Rate': [3.7, 3.8, 3.6, 3.5, 3.4, 3.6]
}

df = pd.DataFrame(data)
df.set_index('Date', inplace=True)
print(df)

This DataFrame is now ready for plotting.

Read Matplotlib log log plot

Method 1: Basic Time Series Plot Using Matplotlib

The simplest way to plot a time series is by using Python Matplotlib’s plot() function directly on the DataFrame.

import matplotlib.pyplot as plt

plt.figure(figsize=(10, 6))
plt.plot(df.index, df['Unemployment_Rate'], marker='o', linestyle='-')
plt.title('Monthly US Unemployment Rate (2023)')
plt.xlabel('Date')
plt.ylabel('Unemployment Rate (%)')
plt.grid(True)
plt.show()

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

plot time series python

This method is quick and easy when you have clean datetime data. I often use it for fast exploratory analysis. The key is to make sure your date column is in datetime format; otherwise, Matplotlib won’t plot it correctly.

Check out Matplotlib subplots_adjust

Method 2: Use Pandas Built-in Plotting with Matplotlib Backend

Pandas integrates Matplotlib, so you can use the DataFrame’s .plot() method, which simplifies the syntax.

df.plot(figsize=(10, 6), marker='o', title='Monthly US Unemployment Rate (2023)')
plt.xlabel('Date')
plt.ylabel('Unemployment Rate (%)')
plt.grid(True)
plt.show()

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

time series plot python

Using pandas plotting is my go-to for quick visualizations because it automatically handles the datetime index on the x-axis. Plus, it’s less code and integrates well when working with pandas data structures.

Read Matplotlib Subplot Tutorial

Method 3: Customize Time Series Plots with Date Formatting

For more professional plots, you might want to customize the date ticks and format the x-axis labels for better readability.

Here’s how I format dates using matplotlib.dates:

import matplotlib.dates as mdates

fig, ax = plt.subplots(figsize=(12, 6))
ax.plot(df.index, df['Unemployment_Rate'], marker='o', linestyle='-')

ax.set_title('Monthly US Unemployment Rate (2023)')
ax.set_xlabel('Date')
ax.set_ylabel('Unemployment Rate (%)')
ax.grid(True)

# Set major ticks format to Month-Year
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))

plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

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

python plot time series

I use this approach when preparing reports or dashboards. The formatted dates make the plot much easier to understand, especially for stakeholders who aren’t data-savvy.

Read Matplotlib Plot Bar Chart

Method 4: Plot Multiple Time Series on the Same Graph

Sometimes, you want to compare multiple time series, like the unemployment rate and the inflation rate, side by side.

Here’s an example:

# Adding inflation rate data
df['Inflation_Rate'] = [2.1, 2.3, 2.2, 2.0, 1.9, 2.1]

fig, ax = plt.subplots(figsize=(12, 6))
ax.plot(df.index, df['Unemployment_Rate'], marker='o', linestyle='-', label='Unemployment Rate')
ax.plot(df.index, df['Inflation_Rate'], marker='x', linestyle='--', label='Inflation Rate')

ax.set_title('US Unemployment and Inflation Rates (2023)')
ax.set_xlabel('Date')
ax.set_ylabel('Rate (%)')
ax.grid(True)

ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))

plt.xticks(rotation=45)
plt.legend()
plt.tight_layout()
plt.show()

Comparing related economic indicators on the same plot can reveal correlations or divergences. I find this very useful when analyzing macroeconomic data for business forecasting.

Check out Matplotlib Dashed Line

Method 5: Add Annotations and Highlights

To emphasize specific events or periods, adding annotations can be very helpful.

For example, highlighting the month when a new policy was introduced:

fig, ax = plt.subplots(figsize=(12, 6))
ax.plot(df.index, df['Unemployment_Rate'], marker='o', linestyle='-')

ax.set_title('Monthly US Unemployment Rate (2023)')
ax.set_xlabel('Date')
ax.set_ylabel('Unemployment Rate (%)')
ax.grid(True)

ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))

# Highlight March 2023
highlight_date = pd.Timestamp('2023-03-31')
highlight_value = df.loc[highlight_date, 'Unemployment_Rate']

ax.annotate('Policy Introduced', xy=(highlight_date, highlight_value), 
            xytext=(highlight_date, highlight_value + 0.3),
            arrowprops=dict(facecolor='red', shrink=0.05),
            fontsize=10, color='red')

plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

Annotations help tell a story with your data. When presenting to executives, these callouts make your points clear and compelling.

Read Matplotlib Best Fit Line

Tips for Effective Time Series Plotting in Matplotlib

  • Always parse dates correctly. Use pd.to_datetime() if needed.
  • Adjust figure size to avoid cramped plots.
  • Use gridlines to improve readability.
  • Rotate x-axis labels for better date visibility.
  • Use legends when plotting multiple series.
  • Format dates to match your audience’s familiarity (e.g., US date format).

Time series plots are essential for analyzing data that changes over time. Matplotlib offers many ways to create these plots, from simple to highly customized.

Whether you’re a data analyst tracking economic indicators or a developer working on financial apps, mastering Matplotlib time series plotting will make your data stories clearer and more impactful.

If you want to explore further, consider combining Matplotlib with libraries like Seaborn or Plotly for interactive and more visually appealing time series plots.

Other Python articles you may also like:

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.