Seaborn lineplot: Line Charts and Time Series

Draw line charts with sns.lineplot: multiple lines with hue and style, wide or long data, date axes, rolling averages, aggregated bands, individual series, and missing values.

sns.lineplot(data=df, x="date", y="value", hue="group") draws a line chart with one line per group. If several rows share an x value, it plots their mean with a 95% confidence band.

Quick Example

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

# Sample data: hourly electricity use for two campus buildings, 12 weeks
rng = np.random.default_rng(65)
times = pd.date_range("2026-03-02", periods=24 * 7 * 12, freq="h")
hour, weekend = times.hour.to_numpy(), times.dayofweek.to_numpy() >= 5
day = np.arange(len(times)) / 24

frames = []
# name, base load, daily swing, trend per day, busiest hour
for building, base, swing, trend, peak in [("Library", 120, 90, -0.25, 15),
                                          ("Lab", 160, 60, 0.45, 11)]:
    open_hours = np.exp(-((hour - peak) ** 2) / 28)
    quiet = np.where(weekend, 0.4 if building == "Library" else 0.2, 1.0)
    kw = base + trend * day + swing * open_hours * quiet + rng.normal(0, 9, len(times))
    frames.append(pd.DataFrame({"time": times, "building": building, "kw": kw}))
hourly = pd.concat(frames, ignore_index=True)

daily = (hourly.groupby(["building", pd.Grouper(key="time", freq="D")])["kw"]
         .sum().rename("kwh").reset_index())
colors = {"Library": "#0f766e", "Lab": "#c026d3"}

sns.set_theme(style="whitegrid")
fig, ax = plt.subplots(figsize=(9, 4.6))
sns.lineplot(data=daily, x="time", y="kwh", hue="building", palette=colors,
             linewidth=1.8, ax=ax)
ax.xaxis.set_major_formatter(mdates.ConciseDateFormatter(ax.xaxis.get_major_locator()))
ax.set(title="Daily electricity use", xlabel="", ylabel="kWh per day")
plt.show()

Seaborn line chart of daily electricity use over 12 weeks for a library and a lab, with weekly dips and a rising trend for the lab

Both buildings dip every weekend, and the lab's use climbs over the 12 weeks while the library's falls. The code targets Seaborn 0.13.

Add a Rolling Average

Seaborn has no smoothing option for time series. Compute the average with pandas, then plot it over the raw values.

daily["weekly_avg"] = (daily.groupby("building")["kwh"]
                       .transform(lambda s: s.rolling(7, center=True).mean()))

fig, ax = plt.subplots(figsize=(9, 4.6))
sns.lineplot(data=daily, x="time", y="kwh", hue="building", palette=colors,
             alpha=0.3, linewidth=1, legend=False, ax=ax)
sns.lineplot(data=daily, x="time", y="weekly_avg", hue="building", palette=colors,
             linewidth=2.8, ax=ax)
ax.xaxis.set_major_formatter(mdates.ConciseDateFormatter(ax.xaxis.get_major_locator()))
ax.set(xlabel="", ylabel="kWh per day")
plt.show()

Faint daily lines with bold seven-day rolling averages showing the lab trending up and the library trending down

The 7-day window covers one full week, so the weekend pattern cancels out. center=True aligns each average with the middle of its window.

Multiple Lines with hue, style, and markers

hue sets color, style sets the dash pattern, and markers=True adds a different marker for each style level.

weekly = (daily.groupby(["building", pd.Grouper(key="time", freq="W")])["kwh"]
          .mean().reset_index())

fig, ax = plt.subplots(figsize=(9, 4.4))
sns.lineplot(data=weekly, x="time", y="kwh", hue="building", style="building",
             markers=True, dashes=False, palette=colors, markersize=8, ax=ax)
ax.xaxis.set_major_formatter(mdates.ConciseDateFormatter(ax.xaxis.get_major_locator()))
ax.set(xlabel="", ylabel="Average kWh per day")
plt.show()

Weekly average electricity lines with circle markers for the lab and cross markers for the library

Using the same column for hue and style keeps lines readable without color. Use two different columns to show two groupings at once. For one fixed look on every line, pass Matplotlib arguments such as linestyle="--" or marker="o".

Plot Every Column of a Wide DataFrame

If each series is its own column, pass the DataFrame as data with no x or y. The index becomes the x-axis and every column becomes a line.

wide = daily.pivot(index="time", columns="building", values="kwh")

fig, ax = plt.subplots(figsize=(9, 4.4))
sns.lineplot(data=wide, palette=colors, dashes=False, ax=ax)
ax.xaxis.set_major_formatter(mdates.ConciseDateFormatter(ax.xaxis.get_major_locator()))
ax.set(xlabel="", ylabel="kWh per day")
plt.show()

Without dashes=False, each column also gets its own dash pattern. To use hue and other grouping options, convert to long form with melt:

long = wide.reset_index().melt(id_vars="time", var_name="building", value_name="kwh")
print(long.head(3))

Repeated x Values: Mean and Confidence Band

Plotting the hourly rows against hour of day gives many observations at each x. Seaborn averages them and draws the band.

hourly["hour"] = hourly["time"].dt.hour
hourly["day_type"] = np.where(hourly["time"].dt.dayofweek >= 5, "Weekend", "Weekday")
lib = hourly[hourly["building"] == "Library"]

fig, axes = plt.subplots(1, 3, figsize=(11, 3.6), sharey=True)
settings = {
    "Mean, 95% CI (default)": {},
    "Median, middle 80%": {"estimator": "median", "errorbar": ("pi", 80)},
    "Mean, no band": {"errorbar": None},
}
for ax, (title, kwargs) in zip(axes, settings.items()):
    sns.lineplot(data=lib, x="hour", y="kw", hue="day_type",
                 palette=["#0f766e", "#f59e0b"], ax=ax, **kwargs)
    ax.set(title=title, xlabel="Hour of day", ylabel="kW", xticks=range(0, 24, 6))
plt.show()

Three panels of library demand by hour: a mean with a narrow confidence band, a median with a wider percentile band, and a mean with no band

A confidence band shows uncertainty about the average. A percentile band ("pi") or "sd" shows how much the observations vary. The confidence interval guide covers each option.

Draw Each Series with units

To see every day as its own line instead of an average, give units the column that identifies each line and set estimator=None.

lib = lib.assign(date=lib["time"].dt.date)

fig, ax = plt.subplots(figsize=(9, 4.4))
sns.lineplot(data=lib, x="hour", y="kw", hue="day_type", units="date",
             estimator=None, palette=["#0f766e", "#f59e0b"], alpha=0.35,
             linewidth=0.8, ax=ax)
ax.set(xlabel="Hour of day", ylabel="kW", xticks=range(0, 24, 3))
plt.show()

Eighty-four thin daily demand lines for the library, teal weekdays peaking higher than orange weekends

Keep the Data Order with sort=False

lineplot sorts by x before drawing. That's wrong for a path, such as a trajectory or two measures traced over time. Pass sort=False, and estimator=None so repeated x values aren't averaged. The lab is busiest in late morning and the library mid-afternoon, so the path forms a loop.

profile = (hourly[hourly["day_type"] == "Weekday"]
           .pivot_table(index="hour", columns="building", values="kw"))

fig, ax = plt.subplots(figsize=(7, 5))
sns.lineplot(data=profile, x="Library", y="Lab", sort=False, estimator=None,
             marker="o", color="#4338ca", ax=ax)
for h in [0, 8, 12, 18]:
    ax.annotate(f"{h}:00", (profile.loc[h, "Library"], profile.loc[h, "Lab"]),
                textcoords="offset points", xytext=(8, 4 if h == 12 else -12))
ax.set(title="Average weekday, hour by hour", xlabel="Library kW", ylabel="Lab kW")
plt.show()

A wide loop of lab demand against library demand across the hours of an average weekday

Show Gaps for Missing Values

lineplot drops missing y values and connects the points on either side, which hides outages. To break the line, number each unbroken stretch and pass it to units.

meter = daily[daily["building"] == "Lab"].reset_index(drop=True)
meter.loc[30:39, "kwh"] = np.nan  # a meter outage
meter["segment"] = meter["kwh"].isna().cumsum()

fig, axes = plt.subplots(2, 1, figsize=(9, 5), sharex=True)
sns.lineplot(data=meter, x="time", y="kwh", color="#c026d3", ax=axes[0])
axes[0].set_title("Default: the gap is bridged")
sns.lineplot(data=meter, x="time", y="kwh", units="segment", estimator=None,
             color="#c026d3", ax=axes[1])
axes[1].set_title("With units: the gap shows")
axes[1].xaxis.set_major_formatter(
    mdates.ConciseDateFormatter(axes[1].xaxis.get_major_locator()))
axes[1].set_xlabel("")
fig.tight_layout()
plt.show()

Two charts of lab electricity use with a ten-day outage, joined by a straight segment in the first and left blank in the second

lineplot or relplot?

lineplot draws on one Axes. sns.relplot(kind="line", col="building", ...) creates a grid with one panel per category and takes the same line options. See figure-level vs axes-level functions. For more control over tick spacing and labels, see custom date formatting.

Similar Topics