Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How can I plot two different spaced time series on one same plot in Python Matplotlib?
When working with time series data, you often need to plot multiple datasets with different time intervals on the same chart. Matplotlib provides excellent tools for handling datetime data and creating professional time series visualizations.
Steps to Plot Multiple Time Series
Set the figure size and adjust the padding between and around the subplots.
Create x1, y1 and x2, y2 data points with different time intervals.
Create a figure and a set of subplots.
Plot both time series using plot_date() method with different markers and line styles.
Format the X-axis ticklabels using DateFormatter.
Rotate xtick labels for better readability using tick_params() method.
Display the figure using show() method.
Example
Here's how to plot two time series with different spacing on the same chart ?
import matplotlib.pyplot as plt
from matplotlib.dates import date2num, DateFormatter
import datetime as dt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
# First time series - 2 data points (8-hour interval)
x1 = [date2num(dt.datetime(2021, 1, 15, 1, 1, 1)),
date2num(dt.datetime(2021, 1, 15, 9, 1, 1))]
y1 = [6, 2]
# Second time series - 5 data points (2-hour intervals)
x2 = [date2num(dt.datetime(2021, 1, 15, 2, 1, 1)),
date2num(dt.datetime(2021, 1, 15, 4, 1, 1)),
date2num(dt.datetime(2021, 1, 15, 6, 1, 1)),
date2num(dt.datetime(2021, 1, 15, 8, 1, 1)),
date2num(dt.datetime(2021, 1, 15, 10, 1, 1))]
y2 = [3, 6, 5, 4, 1]
# Create subplot
fig, ax = plt.subplots()
# Plot both time series with different styles
ax.plot_date(x1, y1, 'o--', label='Series 1')
ax.plot_date(x2, y2, 'o:', label='Series 2')
# Format x-axis to show time
ax.xaxis.set_major_formatter(DateFormatter('%H:%M:%S'))
ax.tick_params(rotation=45)
# Add legend and labels
ax.legend()
ax.set_ylabel('Values')
ax.set_xlabel('Time')
plt.show()
[A time series plot showing two different lines: - Series 1: solid line with circles, showing 2 points at different times - Series 2: dotted line with circles, showing 5 points at regular intervals - X-axis shows time in HH:MM:SS format - Both series plotted on the same axes with different markers and styles]
Alternative Approach Using pandas
For more complex time series data, pandas offers a cleaner approach ?
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# Create sample time series with different frequencies
dates1 = pd.date_range('2021-01-15 01:00:00', periods=3, freq='4H')
values1 = [6, 4, 2]
dates2 = pd.date_range('2021-01-15 02:00:00', periods=5, freq='2H')
values2 = [3, 6, 5, 4, 1]
# Create DataFrame
ts1 = pd.Series(values1, index=dates1, name='Hourly Data')
ts2 = pd.Series(values2, index=dates2, name='Bi-hourly Data')
# Plot both series
plt.figure(figsize=(10, 6))
ts1.plot(marker='o', linestyle='--', linewidth=2)
ts2.plot(marker='s', linestyle=':', linewidth=2)
plt.title('Multiple Time Series with Different Intervals')
plt.xlabel('Time')
plt.ylabel('Values')
plt.legend()
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
[A cleaner time series plot showing: - Two series with different markers (circles and squares) - Automatic time axis formatting - Professional styling with title and legend - Different line styles for easy distinction]
Key Points
date2num() converts datetime objects to Matplotlib's internal date format
DateFormatter() allows custom time format display on axes
plot_date() is specifically designed for time series plotting
Different markers ('o--', 'o:') help distinguish between multiple series
pandas provides more intuitive time series handling for complex datasets
Conclusion
Use plot_date() with DateFormatter for basic time series plotting. For complex time series analysis, pandas offers more powerful and intuitive methods. Always use different markers and line styles to distinguish multiple series clearly.
