How to Plot a Rolling Average in Pandas

Plot a moving average with rolling().mean() and ewm(): window sizes, centered and time-based windows, gaps, rolling median, standard deviation bands, and groups.

To plot a rolling average in pandas, call .rolling(window).mean() on a column and plot the result over the raw values. df["kwh"].rolling(30).mean() averages each row with the 29 rows before it.

Quick Example

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

rng = np.random.default_rng(139)

# Two years of daily output from a rooftop solar array.
days = pd.date_range("2024-01-01", "2025-12-31", name="date")
season = 17 - 10 * np.cos(2 * np.pi * (days.dayofyear + 10) / 365)
clouds = rng.beta(4.0, 1.6, len(days))
df = pd.DataFrame({"kwh": (season * clouds * 1.25).round(2)}, index=days)

df["avg_30"] = df["kwh"].rolling(30).mean()

fig, ax = plt.subplots(figsize=(9, 4.2))
ax.plot(df.index, df["kwh"], color="#f6bd60", linewidth=0.8, label="Daily")
ax.plot(df.index, df["avg_30"], color="#9d0208", linewidth=2.5,
        label="30-day average")
ax.set_ylabel("kWh")
ax.set_title("Solar Output")
ax.legend(loc="upper left", ncols=2)
ax.set_ylim(0, 40)
plt.show()

Noisy daily solar output with a smooth 30-day rolling average that peaks each summer

The data is made up: output rises in summer, and clouds add day-to-day noise. The code targets pandas 3.

Why Does the Line Start Late?

A window of 7 needs 7 values, so the first 6 results are NaN and nothing is drawn for them. min_periods lowers that requirement.

head = df[["kwh"]].head(8).copy()
head["strict"] = head["kwh"].rolling(7).mean()
head["min_periods_1"] = head["kwh"].rolling(7, min_periods=1).mean()
print(head.round(2))

With min_periods=1, the first value is a one-day "average", the second covers two days, and so on. Those early points are noisier than the rest of the line.

The same rule applies to gaps: with the default, one missing value blanks every window that contains it.

Which Window Size Should I Use?

A longer window gives a smoother line that reacts more slowly. Match the window to the cycle you want to remove: 7 days cancels a weekly pattern, and 365 days cancels a yearly one.

fig, ax = plt.subplots(figsize=(9, 4.2))
ax.plot(df["kwh"], color="#ced4da", linewidth=0.8, label="Daily")

for window, color in [(7, "#8ecae6"), (30, "#219ebc"), (90, "#023047")]:
    ax.plot(df["kwh"].rolling(window).mean(), color=color, linewidth=1.8,
            label=f"{window} days")

ax.set_ylabel("kWh")
ax.set_title("Longer Windows Smooth More and Lag More")
ax.legend(loc="upper left", ncols=4)
ax.set_ylim(0, 40)
plt.show()

Rolling averages over 7, 30, and 90 days, with longer windows smoother and shifted further to the right

Center the Window

By default each average sits at the end of its window, so peaks appear late. center=True places it in the middle.

trailing = df["kwh"].rolling(90).mean()
centered = df["kwh"].rolling(90, center=True).mean()

fig, ax = plt.subplots(figsize=(9, 4))
ax.plot(trailing, color="#bc6c25", linewidth=2.2, label="Trailing (default)")
ax.plot(centered, color="#283618", linewidth=2.2, label="center=True")
for year in (2024, 2025):
    ax.axvline(pd.Timestamp(year, 6, 21), color="gray", linestyle=":")
ax.set_ylabel("kWh")
ax.set_title("90-Day Average (dotted lines: June 21)")
ax.set_ylim(0, 27)
ax.legend(loc="lower center")
plt.show()

The centered 90-day average peaks near June 21 while the trailing average peaks about six weeks later

Use a centered window to describe the past. Use a trailing one when the value on each date must only use data available then, as in a live dashboard or a forecasting feature.

Use a Time-Based Window for Missing Dates

rolling(7) counts rows. If some dates are missing, seven rows can span weeks. A string such as "7D" counts calendar days, which requires a datetime index or a datetime column named in on.

# Drop most of three weeks in March, as if the logger was offline.
march = df.loc["2025-02-15":"2025-04-15", "kwh"]
offline = march.loc["2025-03-05":"2025-03-25"].index
gappy = march.drop(offline[offline.day % 6 != 0])

by_rows = gappy.rolling(7).mean()
by_days = gappy.rolling("7D").mean()

fig, ax = plt.subplots(figsize=(9, 4))
ax.plot(gappy, "o", color="#adb5bd", markersize=4, label="Logged days")
ax.plot(by_rows, color="#7209b7", linewidth=2, label="rolling(7): 7 rows")
ax.plot(by_days, color="#4cc9f0", linewidth=2, label='rolling("7D"): 7 days')
ax.set_ylabel("kWh")
ax.set_title("Row Windows and Time Windows With a Gap")
ax.legend(loc="upper left")
ax.xaxis.set_major_formatter(plt.matplotlib.dates.DateFormatter("%b %d"))
ax.set_ylim(0, 36)
plt.show()

Row-based and seven-day rolling averages that differ during and just after a period with few logged days

Time windows default to min_periods=1, so they produce a value even from a single reading. Set min_periods=4, for example, to require four. The index must be sorted, and calendar units without a fixed length, such as months, aren't accepted.

Exponential Moving Average with ewm()

ewm() weights recent values more heavily and lets older ones fade out gradually. The newest values count for more than in a plain average, and a one-off spike fades instead of dropping out of the window all at once.

year = df.loc["2025", "kwh"]

fig, ax = plt.subplots(figsize=(9, 4))
ax.plot(year, color="#dee2e6", linewidth=0.9, label="Daily")
ax.plot(df["kwh"].rolling(30).mean().loc["2025"], color="#457b9d",
        linewidth=2, label="rolling(30)")
ax.plot(df["kwh"].ewm(span=30).mean().loc["2025"], color="#e63946",
        linewidth=2, label="ewm(span=30)")
ax.set_ylabel("kWh")
ax.set_title("Simple vs Exponential Moving Average")
ax.legend(loc="upper left", ncols=3)
ax.set_ylim(0, 40)
plt.show()

A 30-day rolling average and a span-30 exponential moving average over one year of solar output

span=30 gives the newest value a weight of about 2 / (30 + 1). Both averages here are computed on the full data and then sliced, so January already has history behind it. On this data the two lines stay close throughout the year.

Rolling Median for Spikes

One bad reading moves a mean for the whole window. A rolling median mostly ignores it.

spiky = df.loc["2025-06-01":"2025-08-31", "kwh"].copy()
spiky.iloc[[20, 45, 70]] = 95  # logger glitches

fig, ax = plt.subplots(figsize=(9, 4))
ax.plot(spiky, ".", color="#6c757d", label="Daily, with 3 glitches")
ax.plot(spiky.rolling(7, center=True).mean(), color="#f77f00", linewidth=2,
        label="7-day mean")
ax.plot(spiky.rolling(7, center=True).median(), color="#003049", linewidth=2,
        label="7-day median")
ax.set_ylabel("kWh")
ax.set_title("Mean vs Median With Bad Readings")
ax.legend(loc="upper left", ncols=3)
ax.set_ylim(0, 110)
ax.xaxis.set_major_formatter(plt.matplotlib.dates.DateFormatter("%b %d"))
plt.show()

Three glitch readings create flat bumps in the rolling mean while the rolling median stays level

Add a Rolling Standard Deviation Band

agg() computes several statistics over the same window. Shade one standard deviation on each side of the mean with fill_between().

stats = df["kwh"].rolling(30, center=True).agg(["mean", "std"])

fig, ax = plt.subplots(figsize=(9, 4))
ax.fill_between(stats.index, stats["mean"] - stats["std"],
                stats["mean"] + stats["std"], color="#52b788", alpha=0.3,
                linewidth=0, label="± 1 standard deviation")
ax.plot(stats["mean"], color="#1b4332", linewidth=2, label="30-day mean")
ax.set_ylabel("kWh")
ax.set_title("Typical Range of Daily Output")
ax.legend(loc="upper left")
ax.set_ylim(0, 40)
plt.show()

30-day mean solar output with a standard deviation band that is wider in summer than in winter

The band describes how much individual days vary. It isn't a confidence interval for the mean.

Rolling Average by Group

With several series in long format, use groupby() with transform() so one group's values never enter another's window.

other = (df["kwh"] * 0.6 * rng.uniform(0.85, 1.15, len(df))).round(2)
long = pd.concat([
    df[["kwh"]].assign(roof="South roof"),
    pd.DataFrame({"kwh": other, "roof": "East roof"}),
]).reset_index()

long["avg"] = (long.groupby("roof")["kwh"]
               .transform(lambda s: s.rolling(30).mean()))

wide = long.pivot(index="date", columns="roof", values="avg")
ax = wide.plot(figsize=(9, 4), color=["#8338ec", "#fb5607"], linewidth=2)
ax.set_xlabel("")
ax.set_ylabel("kWh")
ax.set_title("30-Day Average by Roof")
ax.legend(title="", loc="upper left")
ax.set_ylim(0, 32)
plt.show()

30-day rolling averages for a south roof and a smaller east roof following the same seasonal pattern

If your data already has one numeric column per series, df.rolling(30).mean() handles them all at once.

rolling, ewm, resample, or expanding?

Method Result Use it for
s.rolling(30).mean() One value per row, from a moving window Smoothing a series
s.ewm(span=30).mean() One value per row, recent values weighted more Putting more weight on recent data
s.resample("MS").mean() One value per period Monthly or weekly summaries
s.expanding().mean() Average of everything so far A long-term running average

Practical Tips

  • Sort by date before using rolling(). A row window on unsorted data runs without an error and gives meaningless results.
  • Compute the average before filtering to a date range, or the start of the chart will be blank.
  • Don't compare the last point of a centered average with earlier ones: it's NaN unless you lower min_periods, and then it covers a shorter window.
  • For long series, downsample before plotting the raw line.

Similar Topics