0
0
Matplotlibdata~5 mins

Multiple time series comparison in Matplotlib

Choose your learning style9 modes available
Introduction

We compare multiple time series to see how different things change over time together. This helps us find patterns or differences easily.

Comparing sales of different products over months to see which sells better.
Tracking temperature changes in different cities over days to find weather trends.
Monitoring stock prices of several companies to spot market movements.
Observing website visits from different sources over weeks to understand traffic.
Syntax
Matplotlib
import matplotlib.pyplot as plt

plt.plot(time1, series1, label='Series 1')
plt.plot(time2, series2, label='Series 2')
plt.xlabel('Time')
plt.ylabel('Value')
plt.title('Multiple Time Series Comparison')
plt.legend()
plt.show()
Use plt.plot() multiple times to add each time series to the same chart.
Add label to each series for the legend to identify them.
Examples
Two simple series with the same time points are plotted and labeled.
Matplotlib
plt.plot([1, 2, 3], [10, 20, 30], label='Series A')
plt.plot([1, 2, 3], [15, 25, 35], label='Series B')
plt.legend()
plt.show()
Plotting sales data for two products over the same dates with axis labels and title.
Matplotlib
plt.plot(dates, sales_product1, label='Product 1')
plt.plot(dates, sales_product2, label='Product 2')
plt.xlabel('Date')
plt.ylabel('Sales')
plt.title('Sales Comparison')
plt.legend()
plt.show()
Sample Program

This code plots two time series with dates on the x-axis and values on the y-axis. Markers help distinguish points. The legend shows which line is which.

Matplotlib
import matplotlib.pyplot as plt
import pandas as pd

# Create sample dates
dates = pd.date_range(start='2024-01-01', periods=5, freq='D')

# Sample data for two time series
series1 = [100, 120, 130, 115, 140]
series2 = [90, 110, 125, 130, 135]

# Plot both series
plt.plot(dates, series1, marker='o', label='Series 1')
plt.plot(dates, series2, marker='s', label='Series 2')

# Add labels and title
plt.xlabel('Date')
plt.ylabel('Value')
plt.title('Multiple Time Series Comparison')
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()
OutputSuccess
Important Notes

Make sure time points align or are comparable for meaningful comparison.

Use different colors or markers to clearly see each series.

Adding grid lines helps read values better.

Summary

Plot multiple time series on the same chart using plt.plot() repeatedly.

Label each series for clarity with label and show legend.

Use axis labels and titles to explain what the chart shows.