Skip to content

plot_subseasonality

yohou.plotting.diagnostics.plot_subseasonality(df, *, columns=None, seasonality='month', kind='mean', show_mean=True, groups=None, facet_n_cols=4, color_palette=None, title=None, x_label=None, y_label=None, width=None, height=None, connect_gaps=False, show_legend=True, resampler=None, line_width=2.0, marker_size=4, marker_opacity=0.8, overlay_opacity=0.15, mean_width=2.0, mean_dash='dash')

Plot seasonal subseries.

Creates one mini subplot per season (e.g. 12 for months, 4 for quarters). Within each subplot the values for that season across all cycles are connected chronologically, with an optional horizontal mean line. This view highlights both the level differences between seasons and any trends within each season over time.

For panel data, returns one figure per member with groups overlaid by colour. When only a single member exists, a plain go.Figure is returned instead of a dict.

Parameters

Name Type Description Default
df DataFrame

Input DataFrame with 'time' column and numeric columns.

required
columns str | list[str] | None

Column(s) to plot. If None, uses all numeric columns except 'time'.

None
seasonality str

Seasonal frequency: "month", "quarter", "weekday", "week", "hour".

"month"
kind (mean, lines, box, violin)

Visualization style within each season subplot:

  • "mean" - aggregated mean-per-cycle line with markers (default).
  • "lines" - one thin line per cycle at overlay_opacity, with the mean line overlaid on top.
  • "box" - one box per cycle showing value distribution.
  • "violin" - one violin per cycle showing value distribution.
"mean"
show_mean bool

Show a horizontal mean line within each season subplot.

True
groups list[str] | None

Panel group prefixes to plot.

None
facet_n_cols int

Number of columns in the subplot grid.

4
color_palette list[str] | None

Custom color palette (one color per group).

None
title str | None

Plot title.

None
x_label str | None

X-axis label.

None
y_label str | None

Y-axis label.

None
width int | None

Plot width in pixels.

None
height int | None

Plot height in pixels.

None
connect_gaps bool

If True, connect lines across missing data gaps.

False
show_legend bool

Whether to display the legend.

True
resampler bool | Literal['widget'] | None

Enable plotly-resampler for large datasets. True returns a FigureResampler, "widget" a FigureWidgetResampler, None reads from get_config.

None
line_width float

Line width for cycle traces.

2.0
marker_size float

Marker size for data points.

4
marker_opacity float

Opacity of scatter markers.

0.8
overlay_opacity float

Opacity of per-cycle lines when kind="lines".

0.15
mean_width float

Line width for the horizontal mean line.

2.0
mean_dash str

Dash style for the mean line.

"dash"

Returns

Type Description
Figure | dict[str, Figure]

Plotly figure for non-panel or single-member data. For panel data with multiple members, a dict keyed by member name.

Examples

>>> import polars as pl
>>> from yohou.plotting import plot_subseasonality
>>> # Create sample time series
>>> df = pl.DataFrame({
...     "time": pl.date_range(pl.date(2020, 1, 1), pl.date(2022, 12, 31), "1d", eager=True),
...     "y": [100 + (i % 30) + (i // 30) * 5 for i in range(1096)],
... })
>>> # Plot monthly subseries
>>> fig = plot_subseasonality(df, columns="y", seasonality="month")
>>> len(fig.data) > 0
True

See Also

plot_seasonality : Plot seasonal overlay. plot_time_series : Plot basic time series.

Source Code

Show/Hide source
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
def plot_subseasonality(
    df: pl.DataFrame,
    *,
    columns: str | list[str] | None = None,
    seasonality: str = "month",
    kind: Literal["mean", "lines", "box", "violin"] = "mean",
    show_mean: bool = True,
    groups: list[str] | None = None,
    facet_n_cols: int = 4,
    color_palette: list[str] | None = None,
    title: str | None = None,
    x_label: str | None = None,
    y_label: str | None = None,
    width: int | None = None,
    height: int | None = None,
    connect_gaps: bool = False,
    show_legend: bool = True,
    resampler: bool | Literal["widget"] | None = None,
    line_width: float = 2.0,
    marker_size: float = 4,
    marker_opacity: float = 0.8,
    overlay_opacity: float = 0.15,
    mean_width: float = 2.0,
    mean_dash: str = "dash",
) -> go.Figure | dict[str, go.Figure]:
    """Plot seasonal subseries.

    Creates one mini subplot per season (e.g. 12 for months, 4 for quarters).
    Within each subplot the values for that season across all cycles are
    connected chronologically, with an optional horizontal mean line.  This
    view highlights both the *level* differences between seasons and any
    *trends within* each season over time.

    For panel data, returns one figure per member with groups overlaid by
    colour.  When only a single member exists, a plain ``go.Figure`` is
    returned instead of a dict.

    Parameters
    ----------
    df : pl.DataFrame
        Input DataFrame with 'time' column and numeric columns.
    columns : str | list[str] | None, default=None
        Column(s) to plot. If None, uses all numeric columns except 'time'.
    seasonality : str, default="month"
        Seasonal frequency: "month", "quarter", "weekday", "week", "hour".
    kind : {"mean", "lines", "box", "violin"}, default="mean"
        Visualization style within each season subplot:

        - ``"mean"`` - aggregated mean-per-cycle line with markers (default).
        - ``"lines"`` - one thin line per cycle at *overlay_opacity*, with
          the mean line overlaid on top.
        - ``"box"`` - one box per cycle showing value distribution.
        - ``"violin"`` - one violin per cycle showing value distribution.
    show_mean : bool, default=True
        Show a horizontal mean line within each season subplot.
    groups : list[str] | None, default=None
        Panel group prefixes to plot.
    facet_n_cols : int, default=4
        Number of columns in the subplot grid.
    color_palette : list[str] | None, default=None
        Custom color palette (one color per group).
    title : str | None, default=None
        Plot title.
    x_label : str | None, default=None
        X-axis label.
    y_label : str | None, default=None
        Y-axis label.
    width : int | None, default=None
        Plot width in pixels.
    height : int | None, default=None
        Plot height in pixels.
    connect_gaps : bool, default=False
        If True, connect lines across missing data gaps.
    show_legend : bool, default=True
        Whether to display the legend.
    resampler : bool | Literal["widget"] | None, default=None
        Enable plotly-resampler for large datasets.  ``True`` returns a
        ``FigureResampler``, ``"widget"`` a ``FigureWidgetResampler``,
        ``None`` reads from `get_config`.
    line_width : float, default=2.0
        Line width for cycle traces.
    marker_size : float, default=4
        Marker size for data points.
    marker_opacity : float, default=0.8
        Opacity of scatter markers.
    overlay_opacity : float, default=0.15
        Opacity of per-cycle lines when ``kind="lines"``.
    mean_width : float, default=2.0
        Line width for the horizontal mean line.
    mean_dash : str, default="dash"
        Dash style for the mean line.

    Returns
    -------
    go.Figure | dict[str, go.Figure]
        Plotly figure for non-panel or single-member data.  For panel
        data with multiple members, a dict keyed by member name.

    Examples
    --------
    >>> import polars as pl
    >>> from yohou.plotting import plot_subseasonality

    >>> # Create sample time series
    >>> df = pl.DataFrame({
    ...     "time": pl.date_range(pl.date(2020, 1, 1), pl.date(2022, 12, 31), "1d", eager=True),
    ...     "y": [100 + (i % 30) + (i // 30) * 5 for i in range(1096)],
    ... })

    >>> # Plot monthly subseries
    >>> fig = plot_subseasonality(df, columns="y", seasonality="month")
    >>> len(fig.data) > 0
    True

    See Also
    --------
    [`plot_seasonality`][yohou.plotting.plot_seasonality] : Plot seasonal overlay.
    [`plot_time_series`][yohou.plotting.plot_time_series] : Plot basic time series.
    """
    validate_plotting_data(df, min_rows=2)
    validate_plotting_params(
        kind=kind,
        valid_kinds={"mean", "lines", "box", "violin"},
        width=width,
        height=height,
    )

    if _auto_detect_panel(df) and groups is None and columns is None:
        groups = []

    if groups is not None:
        plot_columns = resolve_panel_columns(df, groups, columns)
    else:
        plot_columns = validate_plotting_data(df, columns=columns, exclude=["time"])
    df_aug = _add_season_and_cycle(df, seasonality)
    seasons = sorted(df_aug["season"].unique().to_list())
    season_labels = _SEASON_LABELS_MAP.get(seasonality)

    n_seasons = len(seasons)
    nrow = math.ceil(n_seasons / facet_n_cols)

    # Build per-subplot titles
    subplot_titles: list[str] = []
    for s in seasons:
        if season_labels and 1 <= s <= len(season_labels):
            subplot_titles.append(season_labels[s - 1])
        else:
            subplot_titles.append(str(s))

    if groups is not None:
        from yohou.plotting._utils import _group_panel_columns  # noqa: PLC0415

        grouped, all_members = _group_panel_columns(plot_columns)

        # Build one figure per member, groups overlaid by colour.
        figures: dict[str, go.Figure] = {}

        for member in all_members:
            color_mgr = PanelColorManager(color_palette)
            legend_tracker = LegendTracker(show_legend=show_legend)

            mfig = _create_subplots(
                resampler,
                rows=nrow,
                cols=facet_n_cols,
                subplot_titles=subplot_titles,
                shared_yaxes=True,
                vertical_spacing=max(0.04, 0.3 / nrow),
            )

            for si, season_val in enumerate(seasons):
                r = si // facet_n_cols + 1
                c_pos = si % facet_n_cols + 1
                season_df = df_aug.filter(pl.col("season") == season_val)

                for gname, group_cols in grouped.items():
                    # Find this member's column within the group.
                    col_name = next(
                        (c for c in group_cols if _member_name(c) == member),
                        None,
                    )
                    if col_name is None or col_name not in season_df.columns:
                        continue

                    display_name = gname
                    col_color = color_mgr.get_color(gname)

                    lines_info = None
                    if kind != "mean":
                        lines_info = _add_kind_traces(
                            mfig,
                            kind=kind,
                            season_df=season_df,
                            col_name=col_name,
                            display_name=display_name,
                            col_color=col_color,
                            overlay_opacity=overlay_opacity,
                            line_width=line_width,
                            row=r,
                            col=c_pos,
                            legend_tracker=legend_tracker,
                        )

                    if kind in ("mean", "lines"):
                        agg_df = season_df.group_by("cycle").agg(pl.col(col_name).mean()).sort("cycle")
                        cycles = agg_df["cycle"].to_list()
                        values = agg_df[col_name].to_list()
                        if not cycles:
                            continue

                        if lines_info is not None:
                            x_vals = lines_info["midpoints"]
                            x_mean_range = [0.0, lines_info["total"][0]]
                        else:
                            x_vals = cycles
                            x_mean_range = [cycles[0], cycles[-1]]

                        mfig.add_trace(
                            go.Scatter(
                                x=x_vals,
                                y=values,
                                mode="lines+markers",
                                line={"color": col_color, "width": line_width},
                                marker={"size": marker_size, "opacity": marker_opacity},
                                connectgaps=connect_gaps,
                                hovertemplate=_make_hovertemplate(
                                    display_name,
                                    "Cycle",
                                    "Value",
                                ),
                                name=display_name,
                                legendgroup=display_name,
                                showlegend=legend_tracker.should_show(display_name),
                            ),
                            row=r,
                            col=c_pos,
                        )

                        if show_mean:
                            mean_val = agg_df[col_name].mean()
                            if mean_val is not None and len(cycles) >= 2:
                                mfig.add_trace(
                                    go.Scatter(
                                        x=x_mean_range,
                                        y=[mean_val, mean_val],
                                        mode="lines",
                                        line={
                                            "color": col_color,
                                            "width": mean_width,
                                            "dash": mean_dash,
                                        },
                                        name=f"Mean ({display_name})",
                                        legendgroup=display_name,
                                        showlegend=False,
                                        hovertemplate=f"Mean: {mean_val:.2f}<extra></extra>",
                                    ),
                                    row=r,
                                    col=c_pos,
                                )

            mfig = apply_default_layout(
                mfig,
                title=title or f"Seasonal Subseries - {member}",
                x_label=x_label,
                y_label=y_label,
                width=width,
                height=height if height is not None else max(450, nrow * 280),
            )
            mfig.update_layout(showlegend=show_legend)
            figures[member] = mfig

        if len(figures) == 1:
            return next(iter(figures.values()))
        return figures

    # Non-panel path
    fig = _create_subplots(
        resampler,
        rows=nrow,
        cols=facet_n_cols,
        subplot_titles=subplot_titles,
        shared_yaxes=True,
        vertical_spacing=max(0.04, 0.3 / nrow),
    )

    colors = resolve_color_palette(color_palette, len(plot_columns))
    legend_tracker = LegendTracker(show_legend=show_legend)

    for si, season_val in enumerate(seasons):
        r = si // facet_n_cols + 1
        c = si % facet_n_cols + 1
        season_df = df_aug.filter(pl.col("season") == season_val)

        for ci, col_name in enumerate(plot_columns):
            col_color = colors[ci % len(colors)]

            lines_info = None
            if kind != "mean":
                lines_info = _add_kind_traces(
                    fig,
                    kind=kind,
                    season_df=season_df,
                    col_name=col_name,
                    display_name=col_name,
                    col_color=col_color,
                    overlay_opacity=overlay_opacity,
                    line_width=line_width,
                    row=r,
                    col=c,
                    legend_tracker=legend_tracker,
                )

            if kind in ("mean", "lines"):
                agg_df = season_df.group_by("cycle").agg(pl.col(col_name).mean()).sort("cycle")
                cycles = agg_df["cycle"].to_list()
                values = agg_df[col_name].to_list()
                if not cycles:
                    continue

                # When kind="lines", remap x-values to the numeric axis.
                if lines_info is not None:
                    x_vals = lines_info["midpoints"]
                    x_mean_range = [0.0, lines_info["total"][0]]
                else:
                    x_vals = cycles
                    x_mean_range = [cycles[0], cycles[-1]]

                fig.add_trace(
                    go.Scatter(
                        x=x_vals,
                        y=values,
                        mode="lines+markers",
                        line={"color": col_color, "width": line_width},
                        marker={"size": marker_size, "opacity": marker_opacity},
                        connectgaps=connect_gaps,
                        hovertemplate=_make_hovertemplate(col_name, "Cycle", "Value"),
                        name=col_name,
                        legendgroup=col_name,
                        showlegend=legend_tracker.should_show(col_name),
                    ),
                    row=r,
                    col=c,
                )

                if show_mean:
                    mean_val = agg_df[col_name].mean()
                    if mean_val is not None and len(cycles) >= 2:
                        fig.add_trace(
                            go.Scatter(
                                x=x_mean_range,
                                y=[mean_val, mean_val],
                                mode="lines",
                                line={
                                    "color": col_color,
                                    "width": mean_width,
                                    "dash": mean_dash,
                                },
                                name=f"Mean ({col_name})",
                                legendgroup=col_name,
                                showlegend=False,
                                hovertemplate=f"Mean: {mean_val:.2f}<extra></extra>",
                            ),
                            row=r,
                            col=c,
                        )

    fig = apply_default_layout(
        fig,
        title=title or "Seasonal Subseries",
        x_label=x_label,
        y_label=y_label,
        width=width,
        height=height if height is not None else max(450, nrow * 280),
    )
    fig.update_layout(showlegend=show_legend)

    return fig

Tutorials

The following example notebooks use this component:

  • Exploratory Visualization


    Visualization

    Exploratory time series visualisation with raw series plots, rolling statistics overlays, seasonal overlays, subseries diagnostics, distribution boxplots, missing data pattern auditing, outlier detection, and resampling comparison.

    View · Open in marimo

  • Seasonal Analysis


    Visualization

    Seasonal overlays, subseasonal structure, ACF/PACF correlation patterns, and STL decomposition for monthly, quarterly, and long-cycle datasets.

    View · Open in marimo