{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "0",
   "metadata": {},
   "source": [
    "# Bokeh\n",
    "\n",
    "[Bokeh](https://bokeh.org/) builds interactive browser charts from Python: pan, zoom, hover and linked selection.\n",
    "sdvplot's Bokeh adapter adds `add_logos`, `add_wordmarks` and `add_headshots`, each drawn as one `image_url` glyph\n",
    "sized in screen pixels so the images keep their size when you zoom, and `sdvplot.team_colors()` gives the fill\n",
    "colors. Bokeh glyphs cannot sit outside the plot frame, so there are no axis logos (see\n",
    "[Interactive charts](interactive-web.ipynb), which also covers a hover tool on NHL logos and logos in place of\n",
    "axis labels).\n",
    "\n",
    "The data is one completed season each from MLB (ESPN), the NBA (hoopR), the NFL (nflverse) and the WNBA (wehoop),\n",
    "all through sportsdataverse-py."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import polars as pl\n",
    "import sportsdataverse.mlb as mlb\n",
    "import sportsdataverse.nba as nba\n",
    "import sportsdataverse.nfl as nfl\n",
    "import sportsdataverse.wnba as wnba\n",
    "from bokeh.io import output_notebook, show\n",
    "from bokeh.layouts import gridplot\n",
    "from bokeh.models import ColumnDataSource, HoverTool\n",
    "from bokeh.plotting import figure\n",
    "\n",
    "import sdvplot\n",
    "\n",
    "output_notebook(hide_banner=True)\n",
    "NFL_SEASON = 2025  # football names a season by the year it starts\n",
    "SEASON = 2026  # the 2026 MLB and WNBA seasons, and the 2025-26 NBA season"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2",
   "metadata": {},
   "source": [
    "## 1. Team-colored bars with a logo on top\n",
    "\n",
    "`sdvplot.team_colors()` returns one hex color per team, in order, which Bokeh's `vbar` takes as `color`. The logos\n",
    "go on a categorical x axis by passing the team names as x, and sit just above each bar. MLB runs per game, top 12:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3",
   "metadata": {},
   "outputs": [],
   "source": [
    "mlb_runs = (\n",
    "    mlb.espn_mlb_standings(season=SEASON)\n",
    "    .with_columns(rs=pl.col(\"points_for\") / pl.col(\"games_played\"))\n",
    "    .sort([\"rs\", \"team_abbreviation\"], descending=[True, False])\n",
    "    .head(12)\n",
    ")\n",
    "teams = mlb_runs[\"team_abbreviation\"].to_list()\n",
    "source = ColumnDataSource({\"team\": teams, \"rs\": mlb_runs[\"rs\"].to_list(), \"color\": sdvplot.team_colors(\"mlb\", teams)})\n",
    "\n",
    "p = figure(\n",
    "    x_range=teams, frame_width=700, frame_height=380, y_range=(0, mlb_runs[\"rs\"].max() * 1.18),\n",
    "    title=f\"MLB runs scored per game, {SEASON} (top 12; data: ESPN via sportsdataverse-py)\",\n",
    "    y_axis_label=\"Runs per game\", toolbar_location=None,\n",
    ")  # fmt: skip\n",
    "bars = p.vbar(x=\"team\", top=\"rs\", width=0.7, color=\"color\", source=source)\n",
    "p.add_tools(HoverTool(renderers=[bars], tooltips=[(\"Team\", \"@team\"), (\"Runs/game\", \"@rs{0.00}\")]))\n",
    "sdvplot.add_logos(p, teams, (mlb_runs[\"rs\"] + mlb_runs[\"rs\"].max() * 0.07).to_list(), teams, league=\"mlb\", height=0.1)\n",
    "p.xgrid.grid_line_color = None\n",
    "show(p)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4",
   "metadata": {},
   "source": [
    "## 2. Headshots with a hover tool\n",
    "\n",
    "`add_headshots` takes ESPN athlete ids. As with logos, a transparent scatter under the images carries the\n",
    "`HoverTool`, since an `image_url` glyph has no hit testing. NBA scoring leaders, points per game against true\n",
    "shooting:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ESPN files the All-Star games and the NBA Cup final as regular-season games: keep the standard ones\n",
    "schedule = nba.load_nba_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",
    "fga, fta = pl.col(\"field_goals_attempted\"), pl.col(\"free_throws_attempted\")\n",
    "per_player = (\n",
    "    nba.load_nba_player_boxscore(seasons=[SEASON])\n",
    "    .filter(\n",
    "        pl.col(\"game_id\").is_in(schedule[\"game_id\"].implode())\n",
    "        & pl.col(\"did_not_play\").not_()\n",
    "        & pl.col(\"minutes\").is_not_null()\n",
    "    )\n",
    "    .sort(\"game_date\")\n",
    "    .group_by(\"athlete_id\", \"athlete_display_name\", maintain_order=True)\n",
    "    .agg(\n",
    "        games=pl.len(),\n",
    "        team_abbreviation=pl.col(\"team_abbreviation\").last(),  # the team he finished with\n",
    "        ppg=pl.col(\"points\").mean(),\n",
    "        ts=pl.col(\"points\").sum() / (2 * (fga.sum() + 0.44 * fta.sum())),\n",
    "    )\n",
    ")\n",
    "assert per_player[\"games\"].max() <= season_games, \"a player has more games than the schedule\"\n",
    "nba_scorers = (\n",
    "    per_player.filter(pl.col(\"games\") >= 40)\n",
    "    .sort(\"ppg\", descending=True)\n",
    "    .head(15)\n",
    "    .with_columns(pl.col(\"athlete_id\").cast(pl.Int64).cast(pl.Utf8))\n",
    ")\n",
    "\n",
    "source = ColumnDataSource(nba_scorers.to_pandas())\n",
    "p = figure(\n",
    "    frame_width=640, frame_height=440, title=f\"NBA scoring leaders, {SEASON - 1}-{SEASON % 100} (40+ games)\",\n",
    "    x_axis_label=\"True shooting %\", y_axis_label=\"Points per game\",\n",
    ")  # fmt: skip\n",
    "dots = p.scatter(\"ts\", \"ppg\", source=source, size=40, alpha=0)\n",
    "p.add_tools(\n",
    "    HoverTool(\n",
    "        renderers=[dots],\n",
    "        tooltips=[\n",
    "            (\"Player\", \"@athlete_display_name\"),\n",
    "            (\"Team\", \"@team_abbreviation\"),\n",
    "            (\"PPG\", \"@ppg{0.0}\"),\n",
    "            (\"TS%\", \"@ts{0.0%}\"),\n",
    "        ],\n",
    "    )\n",
    ")\n",
    "p.x_range.range_padding = p.y_range.range_padding = 0.15\n",
    "sdvplot.add_headshots(p, nba_scorers[\"ts\"], nba_scorers[\"ppg\"], nba_scorers[\"athlete_id\"], league=\"nba\", height=0.11)\n",
    "show(p)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6",
   "metadata": {},
   "source": [
    "## 3. Wordmarks on a horizontal bar chart\n",
    "\n",
    "`add_wordmarks` works on a categorical y axis the same way: pass the team names as y. The wordmarks sit inside the\n",
    "plot at the end of each bar, and each bar is filled with its team's primary color and outlined in its\n",
    "secondary. The NFL's ten\n",
    "best offenses by EPA per play:"
   ]
  },
  {
   "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",
    "nfl_off = (\n",
    "    weeks.group_by(\"team\", maintain_order=True)\n",
    "    .agg(off_epa=(pl.col(\"passing_epa\") + pl.col(\"rushing_epa\")).sum() / plays.sum())\n",
    "    .sort([\"off_epa\", \"team\"], descending=[True, False])\n",
    "    .head(10)\n",
    "    .reverse()  # Bokeh draws the first factor at the bottom\n",
    ")\n",
    "teams = nfl_off[\"team\"].to_list()\n",
    "top = nfl_off[\"off_epa\"].max()\n",
    "\n",
    "p = figure(\n",
    "    y_range=teams, frame_width=640, frame_height=440, x_range=(0, top * 1.45), toolbar_location=None,\n",
    "    title=f\"NFL offense EPA per play, {NFL_SEASON} regular season (top 10)\", x_axis_label=\"EPA per play\",\n",
    ")  # fmt: skip\n",
    "p.hbar(\n",
    "    y=teams, right=nfl_off[\"off_epa\"].to_list(), height=0.7,\n",
    "    fill_color=sdvplot.team_colors(\"nfl\", teams), line_color=sdvplot.team_colors(\"nfl\", teams, which=\"secondary\"),\n",
    "    line_width=3,\n",
    ")  # fmt: skip\n",
    "sdvplot.add_wordmarks(p, (nfl_off[\"off_epa\"] + top * 0.2).to_list(), teams, teams, league=\"nfl\", height=0.06)\n",
    "p.yaxis.major_label_text_font_size = \"0pt\"  # the wordmarks name the teams\n",
    "p.ygrid.grid_line_color = None\n",
    "show(p)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8",
   "metadata": {},
   "source": [
    "## 4. Linked panels that share one data source\n",
    "\n",
    "Two figures that share a `ColumnDataSource` and an x range stay in step: pan or zoom one and the other follows, and\n",
    "a box selection in either highlights the same teams in both. Call `add_logos` once per figure. WNBA points scored\n",
    "against points allowed, and against three-point attempt rate:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9",
   "metadata": {},
   "outputs": [],
   "source": [
    "wnba_teams = (\n",
    "    wnba.load_wnba_team_boxscore(seasons=[SEASON])\n",
    "    .filter(pl.col(\"season_type\") == 2)\n",
    "    .group_by(\"team_abbreviation\", maintain_order=True)\n",
    "    .agg(\n",
    "        games=pl.len(),\n",
    "        scored=pl.col(\"team_score\").mean(),\n",
    "        allowed=pl.col(\"opponent_team_score\").mean(),\n",
    "        three_rate=pl.col(\"three_point_field_goals_attempted\").sum() / pl.col(\"field_goals_attempted\").sum(),\n",
    "    )\n",
    "    .filter(pl.col(\"games\") > 10)  # drops the All-Star Game's teams\n",
    "    .sort(\"team_abbreviation\")\n",
    ")\n",
    "wnba_teams = wnba_teams.with_columns(color=pl.Series(sdvplot.team_colors(\"wnba\", wnba_teams[\"team_abbreviation\"])))\n",
    "source = ColumnDataSource(wnba_teams.to_pandas())\n",
    "tools = \"pan,box_zoom,box_select,reset\"\n",
    "hover = [\n",
    "    (\"Team\", \"@team_abbreviation\"),\n",
    "    (\"Scored\", \"@scored{0.0}\"),\n",
    "    (\"Allowed\", \"@allowed{0.0}\"),\n",
    "    (\"3PA rate\", \"@three_rate{0.0%}\"),\n",
    "]\n",
    "\n",
    "left = figure(frame_width=330, frame_height=320, tools=tools, tooltips=hover, title=\"Scored vs allowed per game\",\n",
    "              x_axis_label=\"Points scored per game\", y_axis_label=\"Points allowed per game\")  # fmt: skip\n",
    "right = figure(frame_width=330, frame_height=320, tools=tools, tooltips=hover, x_range=left.x_range,\n",
    "               title=\"Scored vs three-point attempt rate\", x_axis_label=\"Points scored per game\",\n",
    "               y_axis_label=\"3PA / FGA\")  # fmt: skip\n",
    "for fig, y in ((left, \"allowed\"), (right, \"three_rate\")):\n",
    "    fig.scatter(\"scored\", y, source=source, size=34, fill_color=\"color\", fill_alpha=0.25, line_color=\"color\",\n",
    "                selection_fill_alpha=0.6, nonselection_fill_alpha=0.05)  # fmt: skip\n",
    "    fig.y_range.range_padding = 0.15\n",
    "    sdvplot.add_logos(\n",
    "        fig, wnba_teams[\"scored\"], wnba_teams[y], wnba_teams[\"team_abbreviation\"], league=\"wnba\", height=0.09\n",
    "    )\n",
    "left.x_range.range_padding = 0.12\n",
    "show(gridplot([[left, right]], toolbar_location=\"right\"))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "sdvplot": {
   "description": "Four Bokeh recipes: team-colored bars with logos, headshots with hover, wordmarks on a horizontal bar chart, and linked panels sharing one data source.",
   "label": "Bokeh",
   "position": 10
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
