How to Create a Matplotlib Time Series Scatter Plot

Visualizing data over time is a task I perform almost daily as a developer. While line charts are the standard, there are many times when a scatter plot is actually the better choice.

In my experience, scatter plots are perfect for identifying outliers in time-based data or showing specific events that don’t necessarily have a continuous flow.

If you have ever struggled with messy date axis labels or overlapping points in Matplotlib, you are in the right place.

In this tutorial, I will show you exactly how to build and customize a Matplotlib time series scatter plot using real-world US-centric examples.

Use a Scatter Plot for Time Series

Often, we default to line plots for time series. However, I’ve found that scatter plots excel when the data is “noisy” or sampled at irregular intervals.

For instance, if you are tracking US stock market “flash crashes” or erratic temperature spikes in a localized region, a line might imply a connection that isn’t there.

A scatter plot keeps the focus on individual data points while still respecting the chronological order of the X-axis.

Method 1: The Basic Time Series Scatter Plot

The simplest way to start is by using the plt.scatter() function combined with Python’s built-in datetime module.

I often use this method when I have a small list of dates, and I want a quick visual check of the distribution.

In the example below, I’ll simulate the daily closing price of a popular US tech stock over two weeks.

import matplotlib.pyplot as plt
from datetime import datetime

# Sample Data: Tech Stock Prices (USD)
dates = [
    datetime(2023, 10, 1), datetime(2023, 10, 2), datetime(2023, 10, 3),
    datetime(2023, 10, 4), datetime(2023, 10, 5), datetime(2023, 10, 8),
    datetime(2023, 10, 9), datetime(2023, 10, 10), datetime(2023, 10, 11)
]
prices = [150.25, 152.10, 149.50, 153.00, 155.20, 154.10, 156.00, 158.50, 157.20]

# Creating the plot
plt.figure(figsize=(10, 6))
plt.scatter(dates, prices, color='blue', edgecolor='black', s=100)

# Adding Labels and Title
plt.title('US Tech Stock Price Distribution (Oct 2023)')
plt.xlabel('Date')
plt.ylabel('Price (USD)')

# Display the plot
plt.grid(True, linestyle='--', alpha=0.6)
plt.show()

You can refer to the screenshot below to see the output.

How to Create a Matplotlib Time Series Scatter Plot

When you pass a list of datetime objects to the X-axis, Matplotlib automatically recognizes them. It scales the axis according to the calendar.

I added edgecolor and s (size) parameters here because it makes the individual points pop, which is crucial for professional-looking reports.

Method 2: Use Pandas for Large US Economic Datasets

When I deal with larger datasets, like US Census data or monthly inflation rates, I always reach for Pandas.

Pandas makes it incredibly easy to parse strings into date objects and handle missing values.

Let’s look at how to plot the US Consumer Price Index (CPI) year-over-year changes using a scatter format.

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# Creating a synthetic dataset representing US CPI data
data = {
    'Date': ['2023-01-01', '2023-02-01', '2023-03-01', '2023-04-01', '2023-05-01', 
             '2023-06-01', '2023-07-01', '2023-08-01', '2023-09-01', '2023-10-01'],
    'CPI_Rate': [6.4, 6.0, 5.0, 4.9, 4.0, 3.0, 3.2, 3.7, 3.7, 3.2]
}

df = pd.DataFrame(data)

# Converting the Date column to datetime objects
df['Date'] = pd.to_datetime(df['Date'])

# Plotting
fig, ax = plt.subplots(figsize=(12, 6))
ax.scatter(df['Date'], df['CPI_Rate'], c=df['CPI_Rate'], cmap='RdYlGn_r', s=150)

# Formatting the Date Axis
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
fig.autofmt_xdate() # Auto-rotate dates

plt.title('US CPI Inflation Rate Changes (2023)')
plt.ylabel('Inflation Rate (%)')
plt.xlabel('Month')
plt.grid(True)
plt.show()

You can refer to the screenshot below to see the output.

Create a Matplotlib Time Series Scatter Plot

In the code above, I used cmap=’RdYlGn_r’. This is a trick I use to make data intuitive: higher inflation shows as red, and lower inflation shows as green.

Using colors adds a third dimension of information to your scatter plot without cluttering the screen.

Format the Date Axis (The Pro Way)

One of the biggest headaches I faced early on was overlapping date labels. If you have 365 days of data, the X-axis becomes a black smudge of text.

To fix this, I use matplotlib.dates locators. This gives you surgical control over how many ticks appear.

Use MonthLocators

If you are plotting data over a year, you don’t need every day labeled. You just need the start of each month.

import matplotlib.dates as mdates

# (Inside your plotting code)
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))

I’ve found that using %b %Y (e.g., Oct 2023) is usually the best format for US audiences as it’s instantly recognizable.

Handle Missing Dates in Time Series

In the US, the stock market is closed on weekends and federal holidays like Thanksgiving or Independence Day.

If you plot these dates, you might see large “gaps” in your scatter plot. While scatter plots handle this better than line plots, you may sometimes want to collapse those gaps.

However, for a “Time Series,” I usually recommend keeping the gaps. It accurately represents the passage of time. If a data point is missing, the scatter plot simply won’t show a dot, which is honest data visualization.

Customize Markers for US Regions

If you are comparing different US states, say, California vs. Texas, you can use different marker styles to distinguish them in the same scatter plot.

I find that using a combination of different shapes (circles, squares, triangles) and colors makes the chart accessible for color-blind users as well.

# Sample: Comparing Two Regions
dates_ca = [datetime(2023, 1, 1), datetime(2023, 2, 1), datetime(2023, 3, 1)]
values_ca = [10, 15, 12]

dates_tx = [datetime(2023, 1, 1), datetime(2023, 2, 1), datetime(2023, 3, 1)]
values_tx = [8, 11, 14]

plt.scatter(dates_ca, values_ca, label='California', marker='o', s=100)
plt.scatter(dates_tx, values_tx, label='Texas', marker='s', s=100)
plt.legend()

Add a Trend Line to a Time Series Scatter

Even though we are using dots, sometimes my clients ask, “Which way is the data heading?”

I usually solve this by overlaying a simple linear regression line. This combines the “individual event” feel of a scatter plot with the “direction” of a line plot.

You can use numpy to calculate the trend line. Note that you have to convert your dates to numbers first, as numpy doesn’t understand datetime objects directly.

import numpy as np

# Convert dates to ordinal numbers for regression
date_nums = mdates.date2num(df['Date'])

# Calculate trend line
z = np.polyfit(date_nums, df['CPI_Rate'], 1)
p = np.poly1d(z)

plt.plot(df['Date'], p(date_nums), "r--", alpha=0.5, label='Trend Line')

Tips for High-Ranking Visualizations

If you want your plots to stand out, pay attention to the “Chart Junk.” I always remove the top and right spines of the plot to give it a modern, clean look.

ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

This is a small change, but it makes your Matplotlib output look like it came from a high-end data journalism site like FiveThirtyEight or The New York Times.

Common Errors to Avoid

I have seen many developers run into the TypeError: float() argument must be a string or a number error.

This almost always happens because you passed a string like “2023-10-01” instead of a proper datetime object.

Always ensure you run pd.to_datetime() or datetime.strptime() before passing your data to the scatter function.

Another tip: if your points are too crowded, try reducing the alpha (transparency). Setting alpha=0.5 allows you to see where points overlap, which is great for high-density US population data.

Creating a scatter plot for a time series in Matplotlib is an easy process once you master date formatting.

I hope this tutorial helped you understand how to manage dates and customize your markers for better data storytelling.

Whether you are tracking US economic trends or personal health metrics, these techniques will make your charts much more professional.

You may also read:

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.