{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "0",
   "metadata": {},
   "source": [
    "# reactable sparklines and gauges\n",
    "\n",
    "reactablefmtr draws small charts inside table cells: `react_sparkline`, `react_sparkbar` and `gauge_chart`.\n",
    "`sdvplot.reactable` ports the three as `reactable_sdv_sparkline`, `reactable_sdv_sparkbar` and `reactable_sdv_gauge`.\n",
    "Each cell is a small inline SVG, so the table needs no extra JavaScript, and each SVG is an image with an\n",
    "`aria-label` that a screen reader reads out (the number of points, the low, the high and the last value). Hovering a\n",
    "chart shows the same summary.\n",
    "\n",
    "A sparkline or sparkbar column holds one list of numbers per row: a polars `List` column or a pandas column of lists\n",
    "both pass through reactable-py unchanged. Give `team_col` and `league` and each row's chart takes that team's color.\n",
    "The recipes below use real 2025-26 NBA, 2026 WNBA, 2025 NFL and 2025-26 NHL data loaded through sportsdataverse-py."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import polars as pl\n",
    "import sportsdataverse.nba as nba\n",
    "import sportsdataverse.nfl as nfl\n",
    "import sportsdataverse.nhl as nhl\n",
    "import sportsdataverse.wnba as wnba\n",
    "from reactable import Column, Reactable, embed_css\n",
    "\n",
    "from sdvplot.reactable import (\n",
    "    reactable_sdv_gauge,\n",
    "    reactable_sdv_logos,\n",
    "    reactable_sdv_sparkbar,\n",
    "    reactable_sdv_sparkline,\n",
    ")\n",
    "\n",
    "SEASON = 2026  # the 2025-26 NBA and NHL seasons and the 2026 WNBA season\n",
    "NFL_SEASON = 2025  # nflverse names a season by the year it starts\n",
    "embed_css()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2",
   "metadata": {},
   "source": [
    "## 1. Sparklines: every NBA team's game-by-game point margin\n",
    "\n",
    "One row per team, one list per row: the team's point margin in each of its 82 regular-season games, in date\n",
    "order (`standard_games` drops the All-Star Game and the NBA Cup final, which ESPN files under the regular season).\n",
    "`highlight_points` marks the season's worst and best nights, and `statline=\"mean\"` draws a dashed line at the team's\n",
    "average margin with its value in the right margin. The line takes each team's primary color from `team_col`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3",
   "metadata": {},
   "outputs": [],
   "source": [
    "def standard_games(schedule):\n",
    "    # the regular season's standard games: ESPN also files the All-Star Game and the in-season cup final there\n",
    "    games = schedule.filter((pl.col(\"season_type\") == 2) & (pl.col(\"type_abbreviation\") == \"STD\"))\n",
    "    return pl.col(\"game_id\").is_in(games[\"game_id\"].implode())\n",
    "\n",
    "\n",
    "nba_games = nba.load_nba_team_boxscore(seasons=[SEASON]).filter(standard_games(nba.load_nba_schedule(seasons=[SEASON])))\n",
    "nba_margins = (\n",
    "    nba_games.sort(\"game_date\")\n",
    "    .group_by(\"team_abbreviation\", maintain_order=True)\n",
    "    .agg(\n",
    "        gp=pl.len(),\n",
    "        w=(pl.col(\"team_winner\") == True).sum(),  # noqa: E712\n",
    "        margin=pl.col(\"team_score\") - pl.col(\"opponent_team_score\"),\n",
    "    )\n",
    "    .with_columns(avg=pl.col(\"margin\").list.mean().round(1), logo=pl.col(\"team_abbreviation\"))\n",
    "    .sort(\"avg\", descending=True)\n",
    "    .select(\"logo\", \"team_abbreviation\", \"w\", \"gp\", \"avg\", \"margin\")\n",
    ")\n",
    "assert nba_margins.height == 30 and nba_margins[\"gp\"].min() == nba_margins[\"gp\"].max() == 82\n",
    "Reactable(\n",
    "    nba_margins,\n",
    "    columns=[\n",
    "        reactable_sdv_logos(league=\"nba\", id=\"logo\", name=\"\", width=50, height=26),\n",
    "        Column(id=\"team_abbreviation\", show=False),\n",
    "        Column(id=\"w\", name=\"W\", width=55),\n",
    "        Column(id=\"gp\", name=\"GP\", width=55),\n",
    "        Column(id=\"avg\", name=\"Avg. margin\", width=95),\n",
    "        reactable_sdv_sparkline(\n",
    "            nba_margins,\n",
    "            id=\"margin\",\n",
    "            name=\"Margin, game by game\",\n",
    "            team_col=\"team_abbreviation\",\n",
    "            league=\"nba\",\n",
    "            highlight_points={\"min\": \"#d7191c\", \"max\": \"#1a9641\"},\n",
    "            statline=\"mean\",\n",
    "            decimals=1,\n",
    "            line_width=1,\n",
    "            width=260,\n",
    "            height=34,\n",
    "            min_width=280,\n",
    "        ),\n",
    "    ],\n",
    "    default_page_size=10,\n",
    "    compact=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4",
   "metadata": {},
   "source": [
    "## 2. Sparkbars: WNBA scoring over each team's last 12 games\n",
    "\n",
    "`reactable_sdv_sparkbar` draws the same kind of list as bars. Here each bar is a team's points in one of its last\n",
    "12 regular-season games; `highlight_bars` colors the best game gold, and `labels=\"last\"` prints the most recent\n",
    "score above its bar. Bars stand on zero, so a 70-point night is visibly shorter than a 100-point one."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5",
   "metadata": {},
   "outputs": [],
   "source": [
    "wnba_games = wnba.load_wnba_team_boxscore(seasons=[SEASON]).filter(\n",
    "    standard_games(wnba.load_wnba_schedule(seasons=[SEASON]))\n",
    ")\n",
    "wnba_last = (\n",
    "    wnba_games.sort(\"game_date\")\n",
    "    .group_by(\"team_abbreviation\", maintain_order=True)\n",
    "    .agg(pts=pl.col(\"team_score\").tail(12), ppg=pl.col(\"team_score\").mean().round(1))\n",
    "    .with_columns(last12=pl.col(\"pts\").list.mean().round(1), logo=pl.col(\"team_abbreviation\"))\n",
    "    .sort(\"last12\", descending=True)\n",
    "    .select(\"logo\", \"team_abbreviation\", \"ppg\", \"last12\", \"pts\")\n",
    ")\n",
    "assert wnba_last.height == 15 and wnba_last[\"pts\"].list.len().min() == 12\n",
    "Reactable(\n",
    "    wnba_last,\n",
    "    columns=[\n",
    "        reactable_sdv_logos(league=\"wnba\", id=\"logo\", name=\"\", width=50, height=26),\n",
    "        Column(id=\"team_abbreviation\", show=False),\n",
    "        Column(id=\"ppg\", name=\"Season PPG\", width=100),\n",
    "        Column(id=\"last12\", name=\"Last 12 PPG\", width=100),\n",
    "        reactable_sdv_sparkbar(\n",
    "            wnba_last,\n",
    "            id=\"pts\",\n",
    "            name=\"Points, last 12 games\",\n",
    "            team_col=\"team_abbreviation\",\n",
    "            league=\"wnba\",\n",
    "            highlight_bars={\"max\": \"#f2b705\"},\n",
    "            labels=\"last\",\n",
    "            width=200,\n",
    "            height=34,\n",
    "            min_width=220,\n",
    "        ),\n",
    "    ],\n",
    "    pagination=False,\n",
    "    compact=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6",
   "metadata": {},
   "source": [
    "## 3. Bars above and below zero: NFL offensive EPA per play, week by week\n",
    "\n",
    "Expected points added per play goes below zero, and a sparkbar hangs those weeks under the zero line. nflverse's\n",
    "weekly team stats give each team's passing and rushing EPA and its dropbacks and carries; the list holds one rate per\n",
    "game the team played. `bandline=\"innerquartiles\"` shades the middle half of each team's weeks, so a steady offense\n",
    "shows a thin band and an erratic one a wide band."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7",
   "metadata": {},
   "outputs": [],
   "source": [
    "weeks = nfl.load_nfl_team_stats([NFL_SEASON]).filter(pl.col(\"season_type\") == \"REG\")\n",
    "plays = pl.col(\"attempts\") + pl.col(\"sacks_suffered\") + pl.col(\"carries\")\n",
    "epa = pl.col(\"passing_epa\") + pl.col(\"rushing_epa\")\n",
    "nfl_weekly = (\n",
    "    weeks.sort(\"week\")\n",
    "    .group_by(\"team\", maintain_order=True)\n",
    "    .agg(season_epa=(epa.sum() / plays.sum()).round(3), weekly=(epa / plays).round(3))\n",
    "    .with_columns(logo=pl.col(\"team\"))\n",
    "    .sort(\"season_epa\", descending=True)\n",
    "    .select(\"logo\", \"team\", \"season_epa\", \"weekly\")\n",
    ")\n",
    "assert nfl_weekly.height == 32 and nfl_weekly[\"weekly\"].list.len().min() == 17\n",
    "Reactable(\n",
    "    nfl_weekly,\n",
    "    columns=[\n",
    "        reactable_sdv_logos(league=\"nfl\", id=\"logo\", name=\"\", width=50, height=26),\n",
    "        Column(id=\"team\", show=False),\n",
    "        Column(id=\"season_epa\", name=\"EPA / play\", width=95),\n",
    "        reactable_sdv_sparkbar(\n",
    "            nfl_weekly,\n",
    "            id=\"weekly\",\n",
    "            name=\"EPA / play by week\",\n",
    "            team_col=\"team\",\n",
    "            league=\"nfl\",\n",
    "            bandline=\"innerquartiles\",\n",
    "            bandline_color=\"#888888\",\n",
    "            width=260,\n",
    "            height=34,\n",
    "            min_width=280,\n",
    "        ),\n",
    "    ],\n",
    "    default_page_size=8,\n",
    "    compact=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8",
   "metadata": {},
   "source": [
    "## 4. Gauges: NBA win percentage\n",
    "\n",
    "`reactable_sdv_gauge` turns one number per row into a half-circle gauge with the value inside. With `min_value` and\n",
    "`max_value` the scale is fixed (a win percentage runs from 0 to 1); without them it runs from 0 to the column's\n",
    "largest absolute value (a negative value fills the gauge by its size, as in reactablefmtr). `team_col` fills each gauge in the team's color, and `number_fmt` takes a function or a format spec.\n",
    "The ten best regular-season records:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9",
   "metadata": {},
   "outputs": [],
   "source": [
    "nba_pct = (\n",
    "    nba_margins.with_columns(pct=(pl.col(\"w\") / pl.col(\"gp\")).round(3))\n",
    "    .sort(\"pct\", descending=True)\n",
    "    .select(\"logo\", \"team_abbreviation\", \"w\", \"gp\", \"pct\")\n",
    "    .head(10)\n",
    ")\n",
    "Reactable(\n",
    "    nba_pct,\n",
    "    columns=[\n",
    "        reactable_sdv_logos(league=\"nba\", id=\"logo\", name=\"\", width=50, height=26),\n",
    "        Column(id=\"team_abbreviation\", show=False),\n",
    "        Column(id=\"w\", name=\"W\", width=60),\n",
    "        Column(id=\"gp\", name=\"GP\", width=60),\n",
    "        reactable_sdv_gauge(\n",
    "            nba_pct,\n",
    "            id=\"pct\",\n",
    "            name=\"Win %\",\n",
    "            team_col=\"team_abbreviation\",\n",
    "            league=\"nba\",\n",
    "            min_value=0,\n",
    "            max_value=1,\n",
    "            number_fmt=\"{:.0%}\".format,\n",
    "            show_min_max=True,\n",
    "            size=2,\n",
    "            align=\"center\",\n",
    "            min_width=130,\n",
    "        ),\n",
    "    ],\n",
    "    compact=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "10",
   "metadata": {},
   "source": [
    "## 5. Gauges on a narrow scale: NHL save percentage\n",
    "\n",
    "Save percentage lives in a narrow band, so a gauge from 0 to 1 would look full for every team. Fixing the scale to\n",
    ".880-.920 spreads the 32 teams out, and a two-color `fill_color` ramps from red (the column's lowest) to green (its\n",
    "highest). NHL regular-season game ids carry `02` after the season's year. The goalie box score counts the shots each\n",
    "goaltender faced, so a team's save percentage is its goalies' saves over the shots against them, summed over the\n",
    "season. An empty-net goal is not a shot any goalie faced, and an own goal is not a shot at all: neither is in the\n",
    "denominator, as in the NHL's own goaltending figures."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "11",
   "metadata": {},
   "outputs": [],
   "source": [
    "nhl_goalies = nhl.load_nhl_goalie_box(seasons=[SEASON]).filter(\n",
    "    pl.col(\"game_id\").cast(pl.String).str.slice(4, 2) == \"02\"\n",
    ")\n",
    "nhl_sv = (\n",
    "    nhl_goalies.group_by(\"team_abbrev\")\n",
    "    .agg(\n",
    "        gp=pl.col(\"game_id\").n_unique(),\n",
    "        sv_pct=(pl.col(\"saves\").sum() / pl.col(\"shots_against\").sum()).round(3),\n",
    "    )\n",
    "    .with_columns(logo=pl.col(\"team_abbrev\"))\n",
    "    .sort(\"sv_pct\", descending=True)\n",
    "    .select(\"logo\", \"team_abbrev\", \"gp\", \"sv_pct\")\n",
    ")\n",
    "assert nhl_sv.height == 32 and nhl_sv[\"gp\"].min() == 82\n",
    "Reactable(\n",
    "    nhl_sv,\n",
    "    columns=[\n",
    "        reactable_sdv_logos(league=\"nhl\", id=\"logo\", name=\"\", width=50, height=26),\n",
    "        Column(id=\"team_abbrev\", show=False),\n",
    "        Column(id=\"gp\", name=\"GP\", width=60),\n",
    "        reactable_sdv_gauge(\n",
    "            nhl_sv,\n",
    "            id=\"sv_pct\",\n",
    "            name=\"Save %\",\n",
    "            fill_color=[\"#d7191c\", \"#1a9641\"],\n",
    "            min_value=0.88,\n",
    "            max_value=0.92,\n",
    "            number_fmt=\".3f\",\n",
    "            show_min_max=True,\n",
    "            size=2,\n",
    "            align=\"center\",\n",
    "            min_width=130,\n",
    "        ),\n",
    "    ],\n",
    "    default_page_size=8,\n",
    "    compact=True,\n",
    ")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "sdvplot": {
   "description": "In-cell charts with reactable: NBA point-margin sparklines, WNBA scoring sparkbars, NFL weekly EPA bars above and below zero, and gauges for NBA win percentage and NHL save percentage.",
   "label": "reactable sparklines and gauges",
   "position": 14
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
