{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "0",
   "metadata": {},
   "source": [
    "# pygal\n",
    "\n",
    "[pygal](https://www.pygal.org/) draws charts as SVG, with hover tooltips built in. sdvplot adds two things to it:\n",
    "`sdvplot.pygal.team_style()` turns a list of teams into a pygal `Style` whose series colors are the team colors, and\n",
    "`add_logos` / `add_wordmarks` / `add_headshots` place images on any XY-family chart (`XY`, `DateLine`,\n",
    "`DateTimeLine`, ...) at the exact spot pygal draws each point. pygal writes axis labels as text, so there are no axis\n",
    "logos; `axis_logos` raises a `TypeError` that says so.\n",
    "\n",
    "The data is one completed season each from the NFL (nflverse), MLB (ESPN), the NBA and men's college basketball\n",
    "(hoopR), the WNBA (wehoop) and the NHL (fastRhockey), all through sportsdataverse-py."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import polars as pl\n",
    "import pygal\n",
    "import sportsdataverse.mbb as mbb\n",
    "import sportsdataverse.mlb as mlb\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 IPython.display import HTML, Image, display\n",
    "\n",
    "import sdvplot\n",
    "import sdvplot.pygal\n",
    "\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, NHL and college basketball season\n",
    "\n",
    "\n",
    "def show_svg(chart):\n",
    "    \"\"\"Show a pygal chart inline as SVG (the logos are drawn while pygal renders).\"\"\"\n",
    "    display(HTML(chart.render(is_unicode=True, disable_xml_declaration=True)))\n",
    "\n",
    "\n",
    "def pad(values, share=0.08):\n",
    "    \"\"\"An axis range with room at both ends, so the logos at the edges are not cut off.\"\"\"\n",
    "    lo, hi = min(values), max(values)\n",
    "    return lo - (hi - lo) * share, hi + (hi - lo) * share"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2",
   "metadata": {},
   "source": [
    "pygal's own notebook display is a PNG through cairosvg; `show_svg` keeps the chart as SVG so its tooltips work.\n",
    "Every chart below renders with the logos, because sdvplot hooks into pygal's render step rather than editing one\n",
    "finished SVG.\n",
    "\n",
    "## 1. A scatter with team logos\n",
    "\n",
    "A pygal scatter is an `XY` chart with `stroke=False`. Give each point a `label` so pygal's tooltip names the team,\n",
    "then call `add_logos` with the same x and y. NFL offense against defense, EPA per play:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3",
   "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_epa = (\n",
    "    weeks.group_by(\"team\", maintain_order=True)\n",
    "    .agg(off_epa=epa.sum() / plays.sum())\n",
    "    .join(\n",
    "        weeks.group_by(team=pl.col(\"opponent_team\"), maintain_order=True).agg(def_epa=epa.sum() / plays.sum()),\n",
    "        on=\"team\",\n",
    "    )\n",
    "    .sort(\"team\")\n",
    ")\n",
    "\n",
    "chart = pygal.XY(\n",
    "    stroke=False, width=800, height=560, dots_size=3, show_legend=False,\n",
    "    xrange=pad(nfl_epa[\"off_epa\"]), range=pad(nfl_epa[\"def_epa\"]),\n",
    "    title=f\"NFL EPA per play, {NFL_SEASON} regular season (lower defense EPA is better)\",\n",
    "    x_title=\"Offense EPA per play\", y_title=\"Defense EPA per play allowed\",\n",
    ")  # fmt: skip\n",
    "chart.add(\"teams\", [{\"value\": (o, d), \"label\": t} for t, o, d in nfl_epa.iter_rows()])\n",
    "sdvplot.add_logos(chart, nfl_epa[\"off_epa\"], nfl_epa[\"def_epa\"], nfl_epa[\"team\"], league=\"nfl\", height=0.08)\n",
    "show_svg(chart)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4",
   "metadata": {},
   "source": [
    "## 2. Wordmarks instead of logos\n",
    "\n",
    "`add_wordmarks` takes the same arguments as `add_logos`. A wordmark is wider than it is tall, so a smaller `height`\n",
    "keeps neighbours apart, and a wordmark with a lot of empty space around its letters draws small. MLB runs scored and allowed per game:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5",
   "metadata": {},
   "outputs": [],
   "source": [
    "mlb_runs = (\n",
    "    mlb.espn_mlb_standings(season=SEASON)\n",
    "    .with_columns(\n",
    "        rs=pl.col(\"points_for\") / pl.col(\"games_played\"), ra=pl.col(\"points_against\") / pl.col(\"games_played\")\n",
    "    )\n",
    "    .sort(\"team_abbreviation\")\n",
    ")\n",
    "\n",
    "chart = pygal.XY(\n",
    "    stroke=False, width=800, height=560, dots_size=2, show_legend=False,\n",
    "    xrange=pad(mlb_runs[\"rs\"]), range=pad(mlb_runs[\"ra\"]),\n",
    "    title=f\"MLB runs scored and allowed per game, {SEASON}\", x_title=\"Runs scored per game\",\n",
    "    y_title=\"Runs allowed per game\",\n",
    ")  # fmt: skip\n",
    "chart.add(\n",
    "    \"teams\", [{\"value\": (s, a), \"label\": t} for t, s, a in mlb_runs.select(\"team_abbreviation\", \"rs\", \"ra\").iter_rows()]\n",
    ")\n",
    "sdvplot.add_wordmarks(chart, mlb_runs[\"rs\"], mlb_runs[\"ra\"], mlb_runs[\"team_abbreviation\"], league=\"mlb\", height=0.07)\n",
    "show_svg(chart)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6",
   "metadata": {},
   "source": [
    "## 3. Team colors on a bar chart\n",
    "\n",
    "`team_style()` works on every pygal chart, not only XY: it returns a `Style` whose colors follow the order you add\n",
    "the series. Add one series per team and each bar takes its team's primary color; a `label` on each value and\n",
    "`print_labels=True` write the team on its bar. The ten NBA teams that took the most threes per game:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7",
   "metadata": {},
   "outputs": [],
   "source": [
    "nba_threes = (\n",
    "    nba.load_nba_team_boxscore(seasons=[SEASON])\n",
    "    .filter(pl.col(\"season_type\") == 2)\n",
    "    .group_by(\"team_id\", \"team_abbreviation\", maintain_order=True)\n",
    "    .agg(games=pl.len(), fg3a=pl.col(\"three_point_field_goals_attempted\").mean())\n",
    "    .filter(pl.col(\"games\") > 10)\n",
    "    .with_columns(pl.col(\"team_id\").cast(pl.Int64).cast(pl.Utf8))\n",
    "    .sort(\"fg3a\", descending=True)\n",
    "    .head(10)\n",
    ")\n",
    "\n",
    "style = sdvplot.pygal.team_style(nba_threes[\"team_id\"], league=\"nba\", font_family=\"sans-serif\")\n",
    "chart = pygal.Bar(\n",
    "    style=style, width=800, height=480, show_legend=False, print_labels=True,\n",
    "    title=f\"NBA three-point attempts per game, {SEASON - 1}-{SEASON % 100} (top 10)\", y_title=\"3PA per game\",\n",
    ")  # fmt: skip\n",
    "for team, fg3a in nba_threes.select(\"team_abbreviation\", \"fg3a\").iter_rows():\n",
    "    chart.add(team, [{\"value\": round(fg3a, 1), \"label\": team}])\n",
    "show_svg(chart)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8",
   "metadata": {},
   "source": [
    "## 4. Player headshots\n",
    "\n",
    "`add_headshots` places ESPN headshots by athlete id. WNBA scoring leaders, points per game against minutes per\n",
    "game (players with at least 20 games):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9",
   "metadata": {},
   "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",
    "per_player = (\n",
    "    wnba.load_wnba_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",
    "    .group_by(\"athlete_id\", \"athlete_display_name\", maintain_order=True)\n",
    "    .agg(games=pl.len(), mpg=pl.col(\"minutes\").mean(), ppg=pl.col(\"points\").mean())\n",
    ")\n",
    "assert per_player[\"games\"].max() <= season_games, \"a player has more games than the schedule\"\n",
    "wnba_players = (\n",
    "    per_player.filter(pl.col(\"games\") >= 20)\n",
    "    .sort(\"ppg\", descending=True)\n",
    "    .head(12)\n",
    "    .with_columns(pl.col(\"athlete_id\").cast(pl.Int64).cast(pl.Utf8))\n",
    ")\n",
    "\n",
    "chart = pygal.XY(\n",
    "    stroke=False, width=800, height=560, dots_size=2, show_legend=False,\n",
    "    xrange=pad(wnba_players[\"mpg\"]), range=pad(wnba_players[\"ppg\"], 0.12),\n",
    "    title=f\"WNBA scoring leaders, {SEASON}\", x_title=\"Minutes per game\", y_title=\"Points per game\",\n",
    ")  # fmt: skip\n",
    "chart.add(\n",
    "    \"players\",\n",
    "    [\n",
    "        {\"value\": (m, p), \"label\": n}\n",
    "        for n, m, p in wnba_players.select(\"athlete_display_name\", \"mpg\", \"ppg\").iter_rows()\n",
    "    ],\n",
    ")\n",
    "sdvplot.add_headshots(\n",
    "    chart, wnba_players[\"mpg\"], wnba_players[\"ppg\"], wnba_players[\"athlete_id\"], league=\"wnba\", height=0.1\n",
    ")\n",
    "show_svg(chart)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "10",
   "metadata": {},
   "source": [
    "## 5. A date line: team colors and a logo at the end of each line\n",
    "\n",
    "`DateLine` is in the XY family, so the logos take dates for x. Here `team_style()` colors the lines and\n",
    "`add_logos` marks where each team finished. Cumulative wins in the standard games\n",
    "of the schedule above, for four WNBA teams spread evenly from the top of the standings to the bottom:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "11",
   "metadata": {},
   "outputs": [],
   "source": [
    "wnba_games = (\n",
    "    wnba.load_wnba_team_boxscore(seasons=[SEASON])\n",
    "    .filter(pl.col(\"game_id\").is_in(schedule[\"game_id\"].implode()))\n",
    "    .sort(\"game_date\")\n",
    "    .with_columns(wins=pl.col(\"team_winner\").cast(pl.Int64).cum_sum().over(\"team_abbreviation\"))\n",
    ")\n",
    "standings = (\n",
    "    wnba_games.group_by(\"team_abbreviation\")\n",
    "    .agg(pl.col(\"wins\").max())\n",
    "    .sort([\"wins\", \"team_abbreviation\"], descending=[True, False])\n",
    ")[\"team_abbreviation\"]\n",
    "n = standings.len()\n",
    "leaders = standings.gather([round(i * (n - 1) / 3) for i in range(4)]).to_list()  # first, last and two between\n",
    "ends_max = wnba_games[\"wins\"].max()\n",
    "\n",
    "chart = pygal.DateLine(\n",
    "    style=sdvplot.pygal.team_style(leaders, league=\"wnba\"), width=800, height=480, dots_size=2,\n",
    "    x_label_rotation=25, legend_at_bottom=True, range=(0, ends_max * 1.12), y_title=\"Wins\",\n",
    "    title=f\"WNBA cumulative wins, {SEASON}\",\n",
    ")  # fmt: skip\n",
    "ends = []\n",
    "for team in leaders:\n",
    "    rows = wnba_games.filter(pl.col(\"team_abbreviation\") == team).select(\"game_date\", \"wins\")\n",
    "    chart.add(team, list(rows.iter_rows()))\n",
    "    ends.append(rows.row(-1))\n",
    "sdvplot.add_logos(chart, [d for d, _ in ends], [w for _, w in ends], leaders, league=\"wnba\", height=0.09)\n",
    "show_svg(chart)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "12",
   "metadata": {},
   "source": [
    "## 6. A dark chart with dark-background logos\n",
    "\n",
    "`team_style()` passes any other `Style` option through, so one call sets the team colors and a dark background.\n",
    "`variant=\"dark\"` picks each team's logo drawn for dark backgrounds. NHL goals for and against per game, with each\n",
    "team its own series so its dot takes its secondary color (the logos name the teams, so the legend is off):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "13",
   "metadata": {},
   "outputs": [],
   "source": [
    "nhl_teams = (\n",
    "    nhl.load_nhl_team_box(seasons=[SEASON])\n",
    "    .filter(pl.col(\"game_id\") // 10_000 % 100 == 2)\n",
    "    .group_by(\"team_abbrev\", maintain_order=True)\n",
    "    .agg(gf=pl.col(\"goals\").mean(), ga=pl.col(\"goals_against\").mean())\n",
    "    .sort(\"team_abbrev\")\n",
    ")\n",
    "\n",
    "dark = sdvplot.pygal.team_style(\n",
    "    nhl_teams[\"team_abbrev\"], league=\"nhl\", which=\"secondary\", background=\"#15171c\", plot_background=\"#15171c\",\n",
    "    foreground=\"#d6d8de\", foreground_strong=\"#ffffff\", foreground_subtle=\"#3a3e48\",\n",
    ")  # fmt: skip\n",
    "chart = pygal.XY(\n",
    "    style=dark, stroke=False, width=800, height=560, dots_size=4, show_legend=False,\n",
    "    xrange=pad(nhl_teams[\"gf\"]), range=pad(nhl_teams[\"ga\"]),\n",
    "    title=f\"NHL goals for and against per game, {SEASON - 1}-{SEASON % 100}\", x_title=\"Goals for per game\",\n",
    "    y_title=\"Goals against per game\", inverse_y_axis=True,\n",
    ")  # fmt: skip\n",
    "for team, gf, ga in nhl_teams.iter_rows():\n",
    "    chart.add(team, [(gf, ga)])\n",
    "sdvplot.add_logos(\n",
    "    chart, nhl_teams[\"gf\"], nhl_teams[\"ga\"], nhl_teams[\"team_abbrev\"], league=\"nhl\", variant=\"dark\", height=0.07\n",
    ")\n",
    "show_svg(chart)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "14",
   "metadata": {},
   "source": [
    "## 7. Export a PNG\n",
    "\n",
    "pygal's `render_to_png()` rasterizes the SVG with cairosvg. cairosvg does not fetch linked images, so pass\n",
    "`embed=True`: sdvplot puts each logo in the SVG as a data URI and the PNG needs no network. The SEC's adjusted\n",
    "offensive and defensive efficiency:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "15",
   "metadata": {
    "sdvplot_gallery": {
     "alt": "pygal scatter of SEC men's basketball adjusted offense against adjusted defense with team logos",
     "title": "SEC adjusted efficiency, a pygal chart exported to PNG"
    },
    "tags": [
     "gallery"
    ]
   },
   "outputs": [],
   "source": [
    "sec = (\n",
    "    mbb.load_mbb_ratings(SEASON)\n",
    "    .join(\n",
    "        sdvplot.teams(\"mbb\").filter(pl.col(\"conference\") == \"Southeastern Conference\").select(\"team_id\", \"name\"),\n",
    "        on=\"team_id\",\n",
    "    )\n",
    "    .sort(\"team_id\")\n",
    ")\n",
    "\n",
    "chart = pygal.XY(\n",
    "    stroke=False, width=900, height=640, dots_size=2, show_legend=False,\n",
    "    xrange=pad(sec[\"adj_o\"]), range=pad(sec[\"adj_d\"]),\n",
    "    title=f\"SEC adjusted efficiency, {SEASON - 1}-{SEASON % 100}\", x_title=\"Adjusted offense (points per 100)\",\n",
    "    y_title=\"Adjusted defense (points allowed per 100)\", inverse_y_axis=True,\n",
    ")  # fmt: skip\n",
    "chart.add(\"teams\", [{\"value\": (o, d), \"label\": n} for n, o, d in sec.select(\"name\", \"adj_o\", \"adj_d\").iter_rows()])\n",
    "sdvplot.add_logos(\n",
    "    chart, sec[\"adj_o\"], sec[\"adj_d\"], sec[\"team_id\"], league=\"mbb\", season=SEASON, height=0.08, embed=True\n",
    ")\n",
    "display(Image(data=chart.render_to_png(dpi=144), width=760))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "sdvplot": {
   "description": "Seven pygal recipes: team-color styles, logos, wordmarks and headshots on SVG scatters, a date line, a dark theme, and a PNG export.",
   "label": "pygal",
   "position": 9
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
