{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "0",
   "metadata": {},
   "source": [
    "# plottable\n",
    "\n",
    "[plottable](https://plottable.readthedocs.io/) draws a table as a matplotlib figure: every cell is an axes, so a\n",
    "column can hold text, a bar or an image, and the finished table saves like any chart. `sdvplot.plottable`\n",
    "adds two `ColumnDefinition` builders: `logo_column` draws each row's team as its logo or wordmark (any variant,\n",
    "any season's mark) and `headshot_column` draws each row's player. `sdvplot.team_colors` supplies the colors for\n",
    "team-tinted rows. The [Tables](tables.md) cookbook shows one MLB table with logos; these five recipes cover the\n",
    "WNBA, NFL, NHL, college football and men's college basketball, through sportsdataverse-py, and end with a\n",
    "square image sized for a social post. Saved images go to a temporary folder."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import tempfile\n",
    "from pathlib import Path\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "import polars as pl\n",
    "import sportsdataverse.cfb as cfb\n",
    "import sportsdataverse.mbb as mbb\n",
    "import sportsdataverse.nfl as nfl\n",
    "import sportsdataverse.nhl as nhl\n",
    "import sportsdataverse.wnba as wnba\n",
    "from IPython.display import Image, display\n",
    "from matplotlib import colormaps\n",
    "from matplotlib.colors import LinearSegmentedColormap, to_rgba\n",
    "from plottable import ColumnDefinition, Table\n",
    "from plottable.cmap import normed_cmap\n",
    "from plottable.plots import bar\n",
    "\n",
    "import sdvplot\n",
    "from sdvplot.plottable import headshot_column, logo_column\n",
    "\n",
    "NFL_SEASON = 2025  # nflverse and cfbfastR name a season by the year it starts\n",
    "SEASON = 2026  # the 2026 WNBA season and the 2025-26 NHL and men's college basketball seasons\n",
    "OUT = Path(tempfile.mkdtemp())  # saved images go here, not into your working folder"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2",
   "metadata": {},
   "source": [
    "## 1. Headshots and bars: the WNBA's leading scorers\n",
    "\n",
    "`headshot_column` draws each row's player from an ESPN athlete id, and `logo_column` draws the team beside the\n",
    "name. The points column uses plottable's `bar` plot function, so each scoring average is a bar with its value\n",
    "written next to it. ESPN files the All-Star Game and the Commissioner's Cup final under the regular season too, so the box scores\n",
    "are first cut to the schedule's standard games, and the cell checks that no one played more games than a team's\n",
    "schedule holds. The 2026 regular season's top ten scorers with 20 or more games:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3",
   "metadata": {
    "sdvplot_gallery": {
     "alt": "A plottable table of the WNBA's ten leading scorers with player headshots, team logos and a bar for points per game",
     "title": "WNBA scoring leaders in plottable, headshots and bars"
    },
    "tags": [
     "gallery"
    ]
   },
   "outputs": [],
   "source": [
    "# ESPN files the All-Star Game and the Commissioner's Cup final as regular-season games: keep the standard ones\n",
    "schedule = wnba.load_wnba_schedule(seasons=[SEASON]).filter(\n",
    "    (pl.col(\"season_type\") == 2) & (pl.col(\"type_abbreviation\") == \"STD\")\n",
    ")\n",
    "season_games = pl.concat([schedule[\"home_id\"], schedule[\"away_id\"]]).value_counts()[\"count\"].max()\n",
    "players = wnba.load_wnba_player_boxscore(seasons=[SEASON]).filter(\n",
    "    pl.col(\"game_id\").is_in(schedule[\"game_id\"].implode()) & ~pl.col(\"did_not_play\")\n",
    ")\n",
    "per_player = (\n",
    "    players.sort(\"game_date\")\n",
    "    .group_by(\"athlete_id\", \"athlete_display_name\", maintain_order=True)\n",
    "    .agg(\n",
    "        team=pl.col(\"team_abbreviation\").last(),\n",
    "        gp=pl.len(),\n",
    "        ppg=pl.col(\"points\").mean(),\n",
    "        rpg=pl.col(\"rebounds\").mean().round(1),\n",
    "        apg=pl.col(\"assists\").mean().round(1),\n",
    "    )\n",
    ")\n",
    "assert per_player[\"gp\"].max() <= season_games, \"a player has more games than the schedule\"\n",
    "scorers = (\n",
    "    per_player.filter(pl.col(\"gp\") >= 20)\n",
    "    .sort(\"ppg\", descending=True)\n",
    "    .head(10)\n",
    "    .with_columns(rank=pl.int_range(1, 11))\n",
    "    .select(\n",
    "        \"rank\", photo=\"athlete_id\", player=\"athlete_display_name\", logo=\"team\", gp=\"gp\", ppg=\"ppg\", rpg=\"rpg\", apg=\"apg\"\n",
    "    )\n",
    "    .to_pandas()\n",
    "    .set_index(\"rank\", drop=False)\n",
    ")\n",
    "fig, ax = plt.subplots(figsize=(10, 7))\n",
    "Table(\n",
    "    scorers,\n",
    "    ax=ax,\n",
    "    index_col=\"rank\",\n",
    "    column_definitions=[\n",
    "        ColumnDefinition(\"rank\", title=\"\", width=0.3),\n",
    "        headshot_column(\"photo\", league=\"wnba\", title=\"\", width=0.6),\n",
    "        ColumnDefinition(\"player\", title=\"Player\", width=1.8, textprops={\"ha\": \"left\", \"weight\": \"bold\"}),\n",
    "        logo_column(\"logo\", league=\"wnba\", title=\"\", width=0.5),\n",
    "        ColumnDefinition(\"gp\", title=\"GP\", width=0.4),\n",
    "        ColumnDefinition(\n",
    "            \"ppg\",\n",
    "            title=\"Points per game\",\n",
    "            width=1.6,\n",
    "            plot_fn=bar,\n",
    "            plot_kw={\n",
    "                \"xlim\": (0, scorers[\"ppg\"].max() * 1.1),\n",
    "                \"annotate\": True,\n",
    "                \"color\": \"#e4572e\",\n",
    "                \"height\": 0.5,\n",
    "                \"formatter\": \"{:.1f}\",\n",
    "            },\n",
    "        ),\n",
    "        ColumnDefinition(\"rpg\", title=\"REB\", width=0.5),\n",
    "        ColumnDefinition(\"apg\", title=\"AST\", width=0.5),\n",
    "    ],\n",
    "    row_divider_kw={\"linewidth\": 0.5, \"linestyle\": (0, (1, 3))},\n",
    ")\n",
    "ax.set_title(f\"The WNBA's top scorers, {SEASON}\", loc=\"left\", fontweight=\"bold\", fontsize=14)\n",
    "fig.text(0.99, 0.01, \"Data: wehoop (ESPN) via sportsdataverse-py\", ha=\"right\", fontsize=8, color=\"grey\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4",
   "metadata": {},
   "source": [
    "## 2. Wordmarks and color scales: NFL EPA\n",
    "\n",
    "`logo_column(mark_type=\"wordmark\")` draws the team's wordmark instead of its logo. The six EPA columns use\n",
    "plottable's `cmap` with `normed_cmap`, which centers each column's color scale on its mean: green is good, so the\n",
    "defensive columns take the reversed map. `group=` puts an Offense and a Defense header over their columns. The\n",
    "twelve best teams of 2025 by EPA per play:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5",
   "metadata": {},
   "outputs": [],
   "source": [
    "weeks = nfl.load_nfl_team_stats([NFL_SEASON]).filter(pl.col(\"season_type\") == \"REG\")\n",
    "dropbacks = pl.col(\"attempts\") + pl.col(\"sacks_suffered\")\n",
    "\n",
    "\n",
    "def epa_rates(by):\n",
    "    return weeks.group_by(team=by, maintain_order=True).agg(\n",
    "        epa=(pl.col(\"passing_epa\") + pl.col(\"rushing_epa\")).sum() / (dropbacks + pl.col(\"carries\")).sum(),\n",
    "        pass_epa=pl.col(\"passing_epa\").sum() / dropbacks.sum(),\n",
    "        rush_epa=pl.col(\"rushing_epa\").sum() / pl.col(\"carries\").sum(),\n",
    "    )\n",
    "\n",
    "\n",
    "nfl_epa = (\n",
    "    epa_rates(pl.col(\"team\"))\n",
    "    .join(epa_rates(pl.col(\"opponent_team\")), on=\"team\", suffix=\"_allowed\")\n",
    "    .sort(\"epa\", descending=True)\n",
    "    .head(12)\n",
    "    .to_pandas()\n",
    "    .set_index(\"team\", drop=False)\n",
    ")\n",
    "good, bad = colormaps[\"PiYG\"], colormaps[\"PiYG\"].reversed()\n",
    "labels = {\"epa\": \"Per play\", \"pass_epa\": \"Dropback\", \"rush_epa\": \"Carry\"}\n",
    "fmt = \"{:+.2f}\"\n",
    "fig, ax = plt.subplots(figsize=(10, 6.5))\n",
    "Table(\n",
    "    nfl_epa,\n",
    "    ax=ax,\n",
    "    index_col=\"team\",\n",
    "    column_definitions=[\n",
    "        logo_column(\"team\", league=\"nfl\", mark_type=\"wordmark\", title=\"\", width=1.4),\n",
    "        *[\n",
    "            ColumnDefinition(\n",
    "                c, title=labels[c], group=\"Offense: EPA\", formatter=fmt, cmap=normed_cmap(nfl_epa[c], good)\n",
    "            )\n",
    "            for c in labels\n",
    "        ],\n",
    "        *[\n",
    "            ColumnDefinition(\n",
    "                f\"{c}_allowed\",\n",
    "                title=labels[c],\n",
    "                group=\"Defense: EPA allowed\",\n",
    "                formatter=fmt,\n",
    "                cmap=normed_cmap(nfl_epa[f\"{c}_allowed\"], bad),\n",
    "            )\n",
    "            for c in labels\n",
    "        ],\n",
    "    ],\n",
    ")\n",
    "ax.set_title(f\"The NFL's twelve best offenses by EPA per play, {NFL_SEASON}\", loc=\"left\", fontweight=\"bold\")\n",
    "fig.text(0.99, 0.01, \"Data: nflverse via sportsdataverse-py\", ha=\"right\", fontsize=8, color=\"grey\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6",
   "metadata": {},
   "source": [
    "## 3. Team-colored rows and track bars: an NHL division\n",
    "\n",
    "`sdvplot.team_colors` returns each team's primary color, and after the table is drawn every row's cells take that\n",
    "color at a quarter opacity (`table.rows[i].set_facecolor`). The points-percentage column is a white `bar` over\n",
    "an outlined track (`plot_bg_bar`) on a 0 to 100% scale. The Atlantic Division's final 2025-26 standings:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7",
   "metadata": {},
   "outputs": [],
   "source": [
    "atlantic = (\n",
    "    nhl.nhl_standings(\"2026-04-16\")\n",
    "    .filter(pl.col(\"division_name\") == \"Atlantic\")\n",
    "    .sort(\"points\", descending=True)\n",
    "    .select(\n",
    "        logo=\"team_abbrev_default\",\n",
    "        w=\"wins\",\n",
    "        l=\"losses\",\n",
    "        otl=\"ot_losses\",\n",
    "        pts=\"points\",\n",
    "        pct=\"point_pctg\",\n",
    "        gd=\"goal_differential\",\n",
    "    )\n",
    "    .to_pandas()\n",
    "    .set_index(\"logo\", drop=False)\n",
    ")\n",
    "fig, ax = plt.subplots(figsize=(8, 6.5))\n",
    "table = Table(\n",
    "    atlantic,\n",
    "    ax=ax,\n",
    "    index_col=\"logo\",\n",
    "    column_definitions=[\n",
    "        logo_column(\"logo\", league=\"nhl\", title=\"\", width=0.6),\n",
    "        ColumnDefinition(\"w\", title=\"W\", width=0.5),\n",
    "        ColumnDefinition(\"l\", title=\"L\", width=0.5),\n",
    "        ColumnDefinition(\"otl\", title=\"OTL\", width=0.5),\n",
    "        ColumnDefinition(\"pts\", title=\"PTS\", width=0.5, textprops={\"weight\": \"bold\"}),\n",
    "        ColumnDefinition(\n",
    "            \"pct\",\n",
    "            title=\"Points %\",\n",
    "            width=1.4,\n",
    "            plot_fn=bar,\n",
    "            plot_kw={\n",
    "                \"xlim\": (0, 1),\n",
    "                \"plot_bg_bar\": True,\n",
    "                \"annotate\": True,\n",
    "                \"color\": \"#ffffff\",\n",
    "                \"height\": 0.4,\n",
    "                \"formatter\": \"{:.0%}\",\n",
    "            },\n",
    "        ),\n",
    "        ColumnDefinition(\"gd\", title=\"Goal diff.\", width=0.7, formatter=\"{:+d}\"),\n",
    "    ],\n",
    "    row_dividers=False,\n",
    ")\n",
    "for i, color in enumerate(sdvplot.team_colors(\"nhl\", atlantic[\"logo\"].tolist())):\n",
    "    table.rows[i].set_facecolor(to_rgba(color, 0.25))\n",
    "ax.set_title(f\"The Atlantic Division, {SEASON - 1}-{SEASON % 100}\", loc=\"left\", fontweight=\"bold\")\n",
    "fig.text(0.99, 0.01, \"Data: NHL standings via sportsdataverse-py\", ha=\"right\", fontsize=8, color=\"grey\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8",
   "metadata": {},
   "source": [
    "## 4. Logos from ESPN ids: college football ratings\n",
    "\n",
    "`logo_column` takes any id system sdvplot resolves; cfbfastR's ratings carry ESPN team ids, so the column reads\n",
    "them with `id_system=\"espn\"` and no name lookup. Two rating systems sit under their own group headers, each\n",
    "column's text colored by its value (`text_cmap` with plottable's `normed_cmap`): green is good, red is\n",
    "poor, and the defensive columns use the reversed scale because allowing less is better. The top fifteen of 2025 by net adjusted EPA per play:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9",
   "metadata": {},
   "outputs": [],
   "source": [
    "summaries = cfb.load_cfb_team_summaries(NFL_SEASON).select(\"team_id\", \"pos_team\", \"conference\")\n",
    "ratings = cfb.load_cfb_ratings(NFL_SEASON)\n",
    "assert summaries.schema[\"team_id\"] == ratings.schema[\"team_id\"]\n",
    "top15 = (\n",
    "    ratings.join(summaries, on=\"team_id\")\n",
    "    .sort(\"net_rank\")\n",
    "    .head(15)\n",
    "    .select(\n",
    "        \"net_rank\",\n",
    "        logo=\"team_id\",\n",
    "        team=\"pos_team\",\n",
    "        conf=\"conference\",\n",
    "        off=\"adj_off_epa\",\n",
    "        dfn=\"adj_def_epa\",\n",
    "        net=\"adj_net\",\n",
    "        fei_off=\"fei_off\",\n",
    "        fei_def=\"fei_def\",\n",
    "        fei_net=\"fei_net\",\n",
    "    )\n",
    "    .to_pandas()\n",
    "    .set_index(\"net_rank\", drop=False)\n",
    ")\n",
    "epa_fmt, fei_fmt = \"{:+.3f}\", \"{:+.2f}\"\n",
    "good = LinearSegmentedColormap.from_list(\"good\", [\"#b2182b\", \"#8c8c8c\", \"#1a7837\"])  # dark enough to read as text\n",
    "\n",
    "\n",
    "def scale(column, cmap=good):\n",
    "    \"\"\"Color a column's text by its value, centered on its median.\"\"\"\n",
    "    return normed_cmap(top15[column], cmap=cmap, num_stds=2)\n",
    "\n",
    "\n",
    "fig, ax = plt.subplots(figsize=(12, 8))\n",
    "Table(\n",
    "    top15,\n",
    "    ax=ax,\n",
    "    index_col=\"net_rank\",\n",
    "    column_definitions=[\n",
    "        ColumnDefinition(\"net_rank\", title=\"#\", width=0.3),\n",
    "        logo_column(\"logo\", league=\"cfb\", id_system=\"espn\", title=\"\", width=0.5),\n",
    "        ColumnDefinition(\"team\", title=\"Team\", width=1.4, textprops={\"ha\": \"left\", \"weight\": \"bold\"}),\n",
    "        ColumnDefinition(\"conf\", title=\"Conf.\", width=1.5, textprops={\"ha\": \"left\", \"color\": \"#555555\"}),\n",
    "        ColumnDefinition(\"off\", title=\"Off.\", group=\"Adjusted EPA per play\", formatter=epa_fmt, text_cmap=scale(\"off\")),\n",
    "        ColumnDefinition(\n",
    "            \"dfn\",\n",
    "            title=\"Def.\",\n",
    "            group=\"Adjusted EPA per play\",\n",
    "            formatter=epa_fmt,\n",
    "            text_cmap=scale(\"dfn\", good.reversed()),\n",
    "        ),\n",
    "        ColumnDefinition(\n",
    "            \"net\",\n",
    "            title=\"Net\",\n",
    "            group=\"Adjusted EPA per play\",\n",
    "            formatter=epa_fmt,\n",
    "            text_cmap=scale(\"net\"),\n",
    "            textprops={\"weight\": \"bold\"},\n",
    "        ),\n",
    "        ColumnDefinition(\"fei_off\", title=\"Off.\", group=\"FEI\", formatter=fei_fmt, text_cmap=scale(\"fei_off\")),\n",
    "        ColumnDefinition(\n",
    "            \"fei_def\", title=\"Def.\", group=\"FEI\", formatter=fei_fmt, text_cmap=scale(\"fei_def\", good.reversed())\n",
    "        ),\n",
    "        ColumnDefinition(\n",
    "            \"fei_net\",\n",
    "            title=\"Net\",\n",
    "            group=\"FEI\",\n",
    "            formatter=fei_fmt,\n",
    "            text_cmap=scale(\"fei_net\"),\n",
    "            textprops={\"weight\": \"bold\"},\n",
    "        ),\n",
    "    ],\n",
    "    even_row_color=\"#f6f6f6\",\n",
    ")\n",
    "ax.set_title(f\"College football's best fifteen by adjusted EPA, {NFL_SEASON}\", loc=\"left\", fontweight=\"bold\")\n",
    "fig.text(0.99, 0.01, \"Data: cfbfastR via sportsdataverse-py\", ha=\"right\", fontsize=8, color=\"grey\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "10",
   "metadata": {},
   "source": [
    "## 5. A square image for social: men's college basketball, dark\n",
    "\n",
    "A social post wants a fixed pixel size, and a plottable table is a matplotlib figure, so the size is the figure's\n",
    "inches times its dpi: 6 by 6 inches at 180 dpi is a 1080 by 1080 image. On a dark background `logo_column`'s\n",
    "`variant=\"dark\"` uses the logos drawn for one. The 2025-26 top ten in adjusted efficiency margin, saved to a file\n",
    "and shown from it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "11",
   "metadata": {
    "sdvplot_gallery": {
     "alt": "A 1080 by 1080 dark plottable table of men's college basketball's top ten teams by adjusted efficiency margin, with dark-variant logos",
     "title": "A square plottable table for social, dark logos"
    },
    "tags": [
     "gallery"
    ]
   },
   "outputs": [],
   "source": [
    "names = mbb.load_mbb_team_boxscore(seasons=[SEASON]).select(\"team_id\", \"team_location\").unique(\"team_id\")\n",
    "mbb_ratings = mbb.load_mbb_ratings(SEASON).with_columns(pl.col(\"team_id\").cast(pl.Int32))  # ids ship as text here\n",
    "assert names.schema[\"team_id\"] == mbb_ratings.schema[\"team_id\"]\n",
    "top10 = (\n",
    "    mbb_ratings.sort(\"rank\")\n",
    "    .head(10)\n",
    "    .join(names, on=\"team_id\", how=\"left\")\n",
    "    .select(\"rank\", logo=\"team_id\", team=\"team_location\", em=\"adj_em\", o=\"adj_o\", d=\"adj_d\")\n",
    "    .to_pandas()\n",
    "    .set_index(\"rank\", drop=False)\n",
    ")\n",
    "BG, FG = \"#14161a\", \"#e8e8e8\"\n",
    "fig, ax = plt.subplots(figsize=(6, 6), facecolor=BG)\n",
    "ax.set_facecolor(BG)\n",
    "Table(\n",
    "    top10,\n",
    "    ax=ax,\n",
    "    index_col=\"rank\",\n",
    "    textprops={\"color\": FG, \"fontsize\": 11},\n",
    "    column_definitions=[\n",
    "        ColumnDefinition(\"rank\", title=\"\", width=0.3, textprops={\"color\": \"#8a909a\"}),\n",
    "        logo_column(\"logo\", league=\"mbb\", id_system=\"espn\", variant=\"dark\", title=\"\", width=0.5),\n",
    "        ColumnDefinition(\"team\", title=\"\", width=1.5, textprops={\"ha\": \"left\", \"weight\": \"bold\"}),\n",
    "        ColumnDefinition(\n",
    "            \"em\", title=\"Margin\", width=0.8, formatter=\"{:+.1f}\", textprops={\"color\": \"#7bd389\", \"weight\": \"bold\"}\n",
    "        ),\n",
    "        ColumnDefinition(\"o\", title=\"Off.\", width=0.6, formatter=\"{:.1f}\"),\n",
    "        ColumnDefinition(\"d\", title=\"Def.\", width=0.6, formatter=\"{:.1f}\"),\n",
    "    ],\n",
    "    col_label_divider_kw={\"color\": \"#3a3f48\"},\n",
    "    row_divider_kw={\"color\": \"#2c3038\", \"linewidth\": 0.6},\n",
    ")\n",
    "fig.suptitle(\n",
    "    f\"Men's college basketball, {SEASON - 1}-{SEASON % 100}\",\n",
    "    x=0.06,\n",
    "    ha=\"left\",\n",
    "    color=FG,\n",
    "    fontweight=\"bold\",\n",
    "    fontsize=15,\n",
    ")\n",
    "fig.text(0.06, 0.915, \"Top ten in adjusted efficiency margin (points per 100 possessions)\", color=\"#a8adb7\", fontsize=9)\n",
    "fig.text(0.94, 0.02, \"Data: hoopR via sportsdataverse-py\", ha=\"right\", fontsize=8, color=\"#8a909a\")\n",
    "path = OUT / \"mbb_top10_square.png\"\n",
    "fig.savefig(path, dpi=180, facecolor=BG)\n",
    "plt.close(fig)\n",
    "print(plt.imread(path).shape[1::-1])\n",
    "display(Image(filename=path, width=540))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "sdvplot": {
   "description": "Five plottable recipes with sdvplot: WNBA headshots with bars, NFL wordmarks on color scales, team-colored NHL rows with track bars, college football logos from ESPN ids under column groups, and a dark 1080 x 1080 image for social.",
   "label": "plottable",
   "position": 8
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
