How to Make a Time Series Plot with Rolling Average in Python?

In this article, we will explore two methods for creating a Python time series plot with a rolling average. Both approaches use popular libraries like Matplotlib, Pandas, and Seaborn, which provide powerful capabilities for data manipulation and visualization. Following these methods will enable you to visualize time series data with a rolling average efficiently and understand its general behavior.

Both methods involve similar sequential steps: loading the data, converting the date column to a DateTime object, calculating the rolling average, and generating the plot. The primary difference lies in the libraries used for plotting.

Sample Data

For this tutorial, we'll create sample time series data directly in Python instead of using external files ?

import pandas as pd
import numpy as np
from datetime import datetime, timedelta

# Create sample time series data
dates = pd.date_range(start='2022-01-01', periods=30, freq='D')
values = np.random.randint(10, 25, size=30) + np.sin(np.arange(30) * 0.2) * 5

data = pd.DataFrame({
    'date': dates,
    'value': values
})

print(data.head())
        date      value
0 2022-01-01  19.000000
1 2022-01-02  17.995734
2 2022-01-03  14.389418
3 2022-01-04  22.778637
4 2022-01-05  16.154508

Method 1: Using Pandas and Matplotlib

This approach uses Matplotlib for plotting and Pandas for data manipulation. Matplotlib provides extensive tools for creating static, animated, and interactive visualizations ?

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime, timedelta

# Create sample data
dates = pd.date_range(start='2022-01-01', periods=30, freq='D')
values = np.random.randint(10, 25, size=30) + np.sin(np.arange(30) * 0.2) * 5

data = pd.DataFrame({
    'date': dates,
    'value': values
})

# Convert date column to datetime and set as index
data['date'] = pd.to_datetime(data['date'])
data.set_index('date', inplace=True)

# Calculate rolling average
window_size = 7
rolling_avg = data['value'].rolling(window=window_size).mean()

# Create the plot
plt.figure(figsize=(12, 6))
plt.plot(data.index, data['value'], label='Actual', alpha=0.7)
plt.plot(data.index, rolling_avg, label=f'{window_size}-Day Rolling Average', linewidth=2)
plt.xlabel('Date')
plt.ylabel('Value')
plt.title('Time Series Plot with Rolling Average')
plt.legend()
plt.grid(True, alpha=0.3)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
[Plot showing time series data with actual values and 7-day rolling average]

Method 2: Using Seaborn and Pandas

This approach uses Seaborn, a high-level visualization library built on Matplotlib. Seaborn provides a simpler interface for creating attractive statistical graphics ?

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

# Create sample data
dates = pd.date_range(start='2022-01-01', periods=30, freq='D')
values = np.random.randint(10, 25, size=30) + np.sin(np.arange(30) * 0.2) * 5

data = pd.DataFrame({
    'date': dates,
    'value': values
})

# Convert date column to datetime and set as index
data['date'] = pd.to_datetime(data['date'])
data.set_index('date', inplace=True)

# Calculate rolling average
window_size = 7
rolling_avg = data['value'].rolling(window=window_size).mean()

# Create plot using Seaborn
plt.figure(figsize=(12, 6))
sns.lineplot(x=data.index, y=data['value'], label='Actual', alpha=0.7)
sns.lineplot(x=data.index, y=rolling_avg, label=f'{window_size}-Day Rolling Average', linewidth=2)
plt.xlabel('Date')
plt.ylabel('Value')
plt.title('Time Series Plot with Rolling Average')
plt.legend()
plt.grid(True, alpha=0.3)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
[Plot showing time series data with actual values and 7-day rolling average using Seaborn styling]

Comparison of Methods

Method Libraries Used Code Complexity Best For
Matplotlib + Pandas matplotlib, pandas Medium Full control over plot appearance
Seaborn + Pandas seaborn, pandas Low Quick, attractive plots with minimal code

Key Parameters

Window Size: Determines how many periods to include in the rolling average. Larger windows create smoother curves but may miss short-term trends.

Alpha: Controls line transparency. Values between 0 (transparent) and 1 (opaque) help distinguish between actual and averaged data.

Linewidth: Controls the thickness of lines. Thicker lines for rolling averages help emphasize the trend.

Conclusion

Both methods effectively create time series plots with rolling averages using Python. Use Matplotlib for maximum customization control, or choose Seaborn for quick, attractive visualizations with minimal code. Rolling averages help smooth out short-term fluctuations and reveal underlying trends in time series data.

Updated on: 2026-03-27T10:31:53+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements