How to plot two Pandas time series on the same plot with legends and secondary Y-axis in Matplotlib?

To plot two Pandas time series on the same plot with legends and secondary Y-axis, we can use Matplotlib's secondary_y parameter. This approach is useful when comparing time series with different scales or units.

Step-by-Step Approach

The process involves creating a DataFrame with time series data, plotting the first series on the primary axis, plotting the second series on the secondary axis, and combining their legends.

Complete Example

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# Set figure parameters
plt.rcParams["figure.figsize"] = [10, 6]
plt.rcParams["figure.autolayout"] = True

# Create time series data
np.random.seed(42)  # For reproducible results
date_range = pd.date_range('2021-04-10', periods=10, freq='D')
df = pd.DataFrame({
    'Temperature': np.random.randn(10) * 5 + 25,  # Temperature data around 25°C
    'Humidity': np.random.randn(10) * 10 + 60     # Humidity data around 60%
}, index=date_range)

print("Sample data:")
print(df.head())
Sample data:
            Temperature   Humidity
2021-04-10    27.482643  66.447401
2021-04-11    22.617923  55.435995
2021-04-12    26.476885  64.230566
2021-04-13    29.240893  54.632917
2021-04-14    21.867558  64.958369

Creating the Plot with Secondary Y-axis

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# Create sample data
np.random.seed(42)
date_range = pd.date_range('2021-04-10', periods=10, freq='D')
df = pd.DataFrame({
    'Temperature': np.random.randn(10) * 5 + 25,
    'Humidity': np.random.randn(10) * 10 + 60
}, index=date_range)

# Plot first series on primary axis
ax1 = df['Temperature'].plot(color='red', label='Temperature (°C)', linewidth=2)

# Plot second series on secondary axis
ax2 = df['Humidity'].plot(color='blue', secondary_y=True, label='Humidity (%)', linewidth=2)

# Get legend handles and labels from both axes
h1, l1 = ax1.get_legend_handles_labels()
h2, l2 = ax2.get_legend_handles_labels()

# Combine legends
ax1.legend(h1 + h2, l1 + l2, loc='upper left')

# Set axis labels
ax1.set_ylabel('Temperature (°C)', color='red')
ax2.set_ylabel('Humidity (%)', color='blue')
ax1.set_xlabel('Date')

# Set title
plt.title('Temperature and Humidity Over Time')

plt.show()
[Plot showing two time series with different y-axes and combined legend]

Alternative Method Using subplots()

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# Create sample data
np.random.seed(42)
date_range = pd.date_range('2021-04-10', periods=10, freq='D')
df = pd.DataFrame({
    'Sales': np.random.randn(10) * 1000 + 5000,
    'Orders': np.random.randn(10) * 20 + 100
}, index=date_range)

# Create figure and primary axis
fig, ax1 = plt.subplots(figsize=(10, 6))

# Plot first series
line1 = ax1.plot(df.index, df['Sales'], color='green', label='Sales ($)', linewidth=2)
ax1.set_ylabel('Sales ($)', color='green')
ax1.set_xlabel('Date')

# Create secondary axis
ax2 = ax1.twinx()
line2 = ax2.plot(df.index, df['Orders'], color='orange', label='Orders', linewidth=2)
ax2.set_ylabel('Orders', color='orange')

# Combine legends
lines = line1 + line2
labels = [l.get_label() for l in lines]
ax1.legend(lines, labels, loc='upper left')

plt.title('Sales and Orders Over Time')
plt.tight_layout()
plt.show()
[Plot showing sales and orders with different scales on separate y-axes]

Key Parameters

Parameter Description Usage
secondary_y=True Creates secondary y-axis For second time series
get_legend_handles_labels() Retrieves legend elements Combines multiple legends
twinx() Creates twin axis Alternative approach

Conclusion

Use secondary_y=True in pandas plot for quick dual-axis charts. For more control, use twinx() with matplotlib subplots. Always combine legends using get_legend_handles_labels() for clarity.

Updated on: 2026-03-25T22:03:56+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements