Skip to content

plot_group_scores

yohou.plotting.evaluation.plot_group_scores(scorer, y_truth, y_pred, *, kind='bar', distribute_by='time', color_palette=None, show_legend=True, title=None, x_label=None, y_label=None, width=None, height=None, bar_opacity=0.85, sort_ascending=None, text_auto=True)

Plot scores broken down by panel group.

Requires panel data where y_truth has group columns (e.g. group__member). Computes the scorer for each group independently and visualises the results.

Parameters

Name Type Description Default
scorer BaseScorer or dict[str, BaseScorer]

Yohou scorer instance.

  • If BaseScorer: single scorer to evaluate per group.
  • If dict: keys are scorer names, values are scorer instances.
required
y_truth DataFrame

Ground truth panel data with "time" and group columns.

required
y_pred DataFrame or dict[str, DataFrame]

Predictions.

  • If DataFrame: single forecast.
  • If dict: keys are model names, values are prediction DataFrames.
required
kind str

Plot kind: "bar" for aggregate bar chart, "box" for box-plot distribution of per-record scores, "heatmap" for a 2D heatmap of groups vs models/scorers.

"bar"
distribute_by str

For kind="box", the dimension whose variability the box plot shows:

  • "time": per-timestep score variability.
  • "vintage": per-vintage score variability.
  • "step": per-step score variability.

Ignored for kind="bar".

"time"
color_palette list[str] | None

Custom colour palette.

None
show_legend bool

Whether to show the legend.

True
title str | None

Plot title.

None
x_label str | None

X-axis label. Defaults to "Group".

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
bar_opacity float

Opacity of bars.

0.85
sort_ascending bool or None

Sort groups by score. True for ascending, False for descending, None for insertion order.

None
text_auto bool

Annotate bars with their values (only for kind="bar").

True

Returns

Type Description
Figure

Plotly figure object.

Raises

Type Description
ValueError

If y_truth does not contain panel group columns.

Examples

>>> import polars as pl
>>> from datetime import datetime
>>> from yohou.metrics import MeanAbsoluteError
>>> from yohou.plotting import plot_group_scores
>>> y_truth = pl.DataFrame({
...     "time": [datetime(2020, 1, i) for i in range(1, 4)],
...     "region__east": [10.0, 20.0, 30.0],
...     "region__west": [15.0, 25.0, 35.0],
... })
>>> y_pred = pl.DataFrame({
...     "vintage_time": [datetime(2019, 12, 31)] * 3,
...     "time": [datetime(2020, 1, i) for i in range(1, 4)],
...     "region__east": [12.0, 19.0, 28.0],
...     "region__west": [14.0, 26.0, 33.0],
... })
>>> fig = plot_group_scores(MeanAbsoluteError(), y_truth, y_pred)
>>> len(fig.data) >= 1
True

See Also

plot_score_time_series : Score over time. plot_score_per_step : Score by horizon step.

Source Code

Show/Hide source
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
def plot_group_scores(
    scorer: BaseScorer | dict[str, BaseScorer],
    y_truth: pl.DataFrame,
    y_pred: pl.DataFrame | dict[str, pl.DataFrame],
    *,
    kind: Literal["bar", "box", "heatmap"] = "bar",
    distribute_by: Literal["time", "vintage", "step"] = "time",
    color_palette: list[str] | None = None,
    show_legend: bool = True,
    title: str | None = None,
    x_label: str | None = None,
    y_label: str | None = None,
    width: int | None = None,
    height: int | None = None,
    bar_opacity: float = 0.85,
    sort_ascending: bool | None = None,
    text_auto: bool = True,
) -> go.Figure:
    """Plot scores broken down by panel group.

    Requires panel data where ``y_truth`` has group columns
    (e.g. ``group__member``). Computes the scorer for each group
    independently and visualises the results.

    Parameters
    ----------
    scorer : BaseScorer or dict[str, BaseScorer]
        Yohou scorer instance.

        - If BaseScorer: single scorer to evaluate per group.
        - If dict: keys are scorer names, values are scorer instances.
    y_truth : pl.DataFrame
        Ground truth panel data with ``"time"`` and group columns.
    y_pred : pl.DataFrame or dict[str, pl.DataFrame]
        Predictions.

        - If DataFrame: single forecast.
        - If dict: keys are model names, values are prediction DataFrames.
    kind : str, default="bar"
        Plot kind: ``"bar"`` for aggregate bar chart, ``"box"`` for
        box-plot distribution of per-record scores, ``"heatmap"`` for
        a 2D heatmap of groups vs models/scorers.
    distribute_by : str, default="time"
        For ``kind="box"``, the dimension whose variability the
        box plot shows:

        - ``"time"``: per-timestep score variability.
        - ``"vintage"``: per-vintage score variability.
        - ``"step"``: per-step score variability.

        Ignored for ``kind="bar"``.
    color_palette : list[str] | None, default=None
        Custom colour palette.
    show_legend : bool, default=True
        Whether to show the legend.
    title : str | None, default=None
        Plot title.
    x_label : str | None, default=None
        X-axis label. Defaults to ``"Group"``.
    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.
    bar_opacity : float, default=0.85
        Opacity of bars.
    sort_ascending : bool or None, default=None
        Sort groups by score. ``True`` for ascending, ``False`` for
        descending, ``None`` for insertion order.
    text_auto : bool, default=True
        Annotate bars with their values (only for ``kind="bar"``).

    Returns
    -------
    go.Figure
        Plotly figure object.

    Raises
    ------
    ValueError
        If ``y_truth`` does not contain panel group columns.

    Examples
    --------
    >>> import polars as pl
    >>> from datetime import datetime
    >>> from yohou.metrics import MeanAbsoluteError
    >>> from yohou.plotting import plot_group_scores

    >>> y_truth = pl.DataFrame({
    ...     "time": [datetime(2020, 1, i) for i in range(1, 4)],
    ...     "region__east": [10.0, 20.0, 30.0],
    ...     "region__west": [15.0, 25.0, 35.0],
    ... })
    >>> y_pred = pl.DataFrame({
    ...     "vintage_time": [datetime(2019, 12, 31)] * 3,
    ...     "time": [datetime(2020, 1, i) for i in range(1, 4)],
    ...     "region__east": [12.0, 19.0, 28.0],
    ...     "region__west": [14.0, 26.0, 33.0],
    ... })

    >>> fig = plot_group_scores(MeanAbsoluteError(), y_truth, y_pred)
    >>> len(fig.data) >= 1
    True

    See Also
    --------
    [`plot_score_time_series`][yohou.plotting.plot_score_time_series] : Score over time.
    [`plot_score_per_step`][yohou.plotting.plot_score_per_step] : Score by horizon step.
    """
    validate_plotting_data(y_truth)
    validate_plotting_params(kind=kind, valid_kinds={"bar", "box", "heatmap"}, width=width, height=height)

    y_pred_dict = _normalize_y_pred(y_pred)
    scorer_dict = _normalize_scorers(scorer)

    # Detect panel groups
    _, panel_groups = inspect_panel(y_truth)
    if not panel_groups:
        msg = (
            "y_truth does not contain panel group columns (e.g. 'group__member'). "
            "plot_group_scores requires panel data."
        )
        raise ValueError(msg)

    group_names = sorted(panel_groups)
    n_models = len(y_pred_dict)

    if kind == "bar":
        # Compute aggregate score per group per model per scorer
        # For bar chart: x-axis = groups, one bar per model (for single scorer)
        #                or grouped by scorer x model

        all_entries: list[tuple[str, str, str, float]] = []  # (scorer, model, group, score)

        for s_name, s_orig in scorer_dict.items():
            for m_name, y_pm in y_pred_dict.items():
                validate_plotting_data(y_pm)
                for gname in group_names:
                    g_truth_cols = ["time"] + [c for c in y_truth.columns if c.startswith(f"{gname}__")]
                    g_pred_cols = [
                        c for c in y_pm.columns if c in ("time", "vintage_time") or c.startswith(f"{gname}__")
                    ]
                    y_truth_g = y_truth.select(g_truth_cols)
                    y_pm_g = y_pm.select(g_pred_cols)

                    s_agg = copy.deepcopy(s_orig)
                    s_agg.fit(y_truth_g)
                    score_val = s_agg.score(y_truth_g, y_pm_g)

                    if isinstance(score_val, pl.DataFrame):
                        score_cols = [
                            c for c in score_val.columns if c not in ("time", "vintage_time", "forecasting_step")
                        ]
                        group_score = float(score_val.select(score_cols).mean_horizontal().mean())  # type: ignore
                    else:
                        group_score = float(score_val)  # type: ignore
                    all_entries.append((s_name, m_name, gname, group_score))

        # Build grouped bar chart
        n_scorers = len(scorer_dict)
        multi_scorer = n_scorers > 1

        if multi_scorer and n_models > 1:
            # Series = model x scorer combination
            series_labels = [f"{m} / {s}" for s in scorer_dict for m in y_pred_dict]
        elif multi_scorer:
            series_labels = list(scorer_dict.keys())
        else:
            series_labels = list(y_pred_dict.keys())

        colors = resolve_color_palette(color_palette, len(series_labels))

        # Optional sorting by first series
        if sort_ascending is not None and all_entries:
            first_series_scores = {
                e[2]: e[3]
                for e in all_entries
                if (e[0] == list(scorer_dict.keys())[0] and e[1] == list(y_pred_dict.keys())[0])
            }
            group_names = sorted(
                group_names,
                key=lambda g: first_series_scores.get(g, 0.0),
                reverse=not sort_ascending,
            )

        fig = go.Figure()
        series_idx = 0

        for s_name in scorer_dict:
            for m_name in y_pred_dict:
                values = []
                for gn in group_names:
                    match = [e[3] for e in all_entries if e[0] == s_name and e[1] == m_name and e[2] == gn]
                    values.append(match[0] if match else 0.0)

                if multi_scorer and n_models > 1:
                    label = f"{m_name} / {s_name}"
                elif multi_scorer:
                    label = s_name
                else:
                    label = m_name

                bar_kwargs: dict = {
                    "x": group_names,
                    "y": values,
                    "name": label,
                    "marker_color": colors[series_idx % len(colors)],
                    "opacity": bar_opacity,
                }
                if text_auto:
                    bar_kwargs["text"] = [f"{v:.3g}" for v in values]
                    bar_kwargs["textposition"] = "outside"

                fig.add_trace(go.Bar(**bar_kwargs))
                series_idx += 1

        fig.update_layout(barmode="group")

        if multi_scorer:
            default_title = title or "Group Scores"
            default_y = y_label or "Score"
        else:
            first_scorer = next(iter(scorer_dict.values()))
            scorer_name = first_scorer.__class__.__name__
            default_title = title or f"{scorer_name} by Group"
            default_y = y_label or scorer_name

        fig = apply_default_layout(
            fig,
            title=default_title,
            x_label=x_label or "Group",
            y_label=default_y,
            width=width,
            height=height,
        )
        fig.update_layout(showlegend=show_legend)
        return fig

    if kind == "heatmap":
        # Heatmap: groups on y-axis, models/scorers on x-axis, score as color
        all_entries: list[tuple[str, str, str, float]] = []

        for s_name, s_orig in scorer_dict.items():
            for m_name, y_pm in y_pred_dict.items():
                validate_plotting_data(y_pm)
                for gname in group_names:
                    g_truth_cols = ["time"] + [c for c in y_truth.columns if c.startswith(f"{gname}__")]
                    g_pred_cols = [
                        c for c in y_pm.columns if c in ("time", "vintage_time") or c.startswith(f"{gname}__")
                    ]
                    y_truth_g = y_truth.select(g_truth_cols)
                    y_pm_g = y_pm.select(g_pred_cols)

                    s_agg = copy.deepcopy(s_orig)
                    s_agg.fit(y_truth_g)
                    score_val = s_agg.score(y_truth_g, y_pm_g)

                    if isinstance(score_val, pl.DataFrame):
                        score_cols = [
                            c for c in score_val.columns if c not in ("time", "vintage_time", "forecasting_step")
                        ]
                        group_score = float(score_val.select(score_cols).mean_horizontal().mean())  # type: ignore
                    else:
                        group_score = float(score_val)  # type: ignore
                    all_entries.append((s_name, m_name, gname, group_score))

        n_scorers = len(scorer_dict)
        multi_scorer = n_scorers > 1

        if multi_scorer and n_models > 1:
            series_labels = [f"{m} / {s}" for s in scorer_dict for m in y_pred_dict]
        elif multi_scorer:
            series_labels = list(scorer_dict.keys())
        else:
            series_labels = list(y_pred_dict.keys())

        # Build z-matrix: rows = groups, cols = series
        z_matrix: list[list[float]] = []
        for gname in group_names:
            row: list[float] = []
            for s_name in scorer_dict:
                for m_name in y_pred_dict:
                    match = [e[3] for e in all_entries if e[0] == s_name and e[1] == m_name and e[2] == gname]
                    row.append(match[0] if match else 0.0)
            z_matrix.append(row)

        # Auto-select colorscale direction
        first_scorer = next(iter(scorer_dict.values()))
        lower_better = getattr(first_scorer, "_lower_is_better", True)
        colorscale = "Blues" if lower_better else "Blues_r"

        text_vals = [[f"{v:.3g}" for v in row] for row in z_matrix] if text_auto else None

        fig = go.Figure(
            data=go.Heatmap(
                z=z_matrix,
                x=series_labels,
                y=group_names,
                colorscale=colorscale,
                text=text_vals,
                texttemplate="%{text}" if text_auto else "",
                hovertemplate="Group: %{y}<br>%{x}: %{z:.3g}<extra></extra>",
            )
        )

        scorer_name = first_scorer.__class__.__name__
        default_title = title or ("Group Scores" if multi_scorer else f"{scorer_name} by Group")

        fig = apply_default_layout(
            fig,
            title=default_title,
            x_label=x_label
            or (
                "Model / Scorer"
                if multi_scorer and n_models > 1
                else "Model"
                if n_models > 1
                else "Scorer"
                if multi_scorer
                else "Model"
            ),
            y_label=y_label or "Group",
            width=width,
            height=height,
        )
        fig.update_layout(showlegend=False)
        return fig

    # kind="box": distribution of per-record scores across groups
    # Use componentwise or stepwise/vintagewise aggregation depending on distribute_by
    agg_map = {
        "time": "componentwise",
        "vintage": "stepwise",
        "step": "vintagewise",
    }
    agg_method = agg_map[distribute_by]

    first_scorer = next(iter(scorer_dict.values()))
    first_y_pred = next(iter(y_pred_dict.values()))

    s_cw = copy.deepcopy(first_scorer)
    if isinstance(s_cw, BaseIntervalScorer):
        s_cw.set_params(aggregation_method=[agg_method, "coveragewise"])
    else:
        s_cw.set_params(aggregation_method=agg_method)
    s_cw.fit(y_truth)

    scores_df = s_cw.score(y_truth, first_y_pred)
    if not isinstance(scores_df, pl.DataFrame):
        msg = f"Scorer must return DataFrame for {agg_method} aggregation, got {type(scores_df).__name__}"
        raise TypeError(msg)

    colors = resolve_color_palette(color_palette, len(group_names))
    fig = go.Figure()

    for g_idx, gname in enumerate(group_names):
        g_cols = [c for c in scores_df.columns if c.startswith(f"{gname}__")]
        if not g_cols:
            continue
        if len(g_cols) == 1:
            g_scores = scores_df[g_cols[0]].drop_nulls().to_numpy()
        else:
            g_scores = scores_df.select(g_cols).to_numpy().flatten()
            g_scores = g_scores[~np.isnan(g_scores)]

        fig.add_trace(
            go.Box(
                y=g_scores,
                name=gname,
                marker_color=colors[g_idx % len(colors)],
                boxmean=True,
            )
        )

    scorer_name = first_scorer.__class__.__name__
    fig = apply_default_layout(
        fig,
        title=title or f"{scorer_name} Distribution by Group",
        x_label=x_label or "Group",
        y_label=y_label or scorer_name,
        width=width,
        height=height,
    )
    fig.update_layout(showlegend=show_legend)
    return fig

Tutorials

The following example notebooks use this component:

  • How to Visualize Forecast Evaluation Results


    Visualization

    Use plot_calibration, plot_score_per_step, and plot_forecast to diagnose forecast accuracy and interval calibration visually.

    View · Open in marimo