Skip to main content
Version: main

sdvplot.matplotlib

The matplotlib adapter: logos, wordmarks and headshots on Axes, single-Axes Figures and seaborn grids.

NameWhat it is
add_binsDraw hexagonal or square bins, colored by count or weight, as one PolyCollection (ax.hexbin).
add_headshotsDraw each player's headshot centred on its (x, y) point of a matplotlib or seaborn plot.
add_imagesDraw any image, by local path or URL, centred on each (x, y) point of a matplotlib or seaborn plot.
add_logosDraw each team's logo centred on its (x, y) point of a matplotlib or seaborn plot.
add_wordmarksDraw each team's wordmark centred on its (x, y) point of a matplotlib or seaborn plot.
axis_logosReplace a team axis' tick labels with the teams' logos (or wordmarks), or a player axis' with headshots.
team_tiersA tier list: each team's logo in its tier's row, tier 1 on top, on a dark (sdvplotR) or light theme.
title_imageSet the plot title and draw an image (a team logo, or any image) beside it.

add_bins​

add_bins(
target: Any,
x: Any,
y: Any,
*,
shape: Literal['hex', 'square'] = 'hex',
radius: float | None = None,
side: float | None = None,
equal_area: bool = False,
ids: Any = None,
weights: Any = None,
origin: tuple[float, float] = (0.0, 0.0),
value: Literal['count', 'weight'] = 'count',
fill: float | None = None,
min_count: int = 1,
**kwargs: Any,
) -> Any

Draw hexagonal or square bins, colored by count or weight, as one PolyCollection (ax.hexbin).

The cells are sdvplot.binner's, in data units, so a hex chart and a square chart of the same shots (and an sdvplot-js chart of them) bin every point alike. Only cells with points are drawn (ax.hexbin's mincnt=1). The collection's array is the counts (or the weights, value="weight"), so fig.colorbar(ax.collections[-1]) keys it; its gid is "sdvplot_bins" and it keeps the bins as sdvplot_bins (a list of Bin, in draw order).

Linking: matplotlib draws static images, so there is no selection to share. With picker=True a pick_event's event.ind indexes sdvplot_bins, whose rows and ids name the points in the cell.

Arguments​

NameTypeDescription
targetAnyA matplotlib Axes (or a one-Axes Figure or seaborn grid).
xAnyThe points' x values, in the Axes' data units (e.g. court_x from sdvplot.court_coords).
yAnyThe points' y values.
shapeLiteral['hex', 'square']"hex" (the default) or "square".
radiusfloat | NoneThe hexagon's circumradius, in data units; for squares, with equal_area=True.
sidefloat | NoneThe square's side (shape="square").
equal_areaboolSquares of a radius-radius hexagon's area.
idsAnyOptional link ids, one per point (default the row number); see sdvplot.hexbin.
weightsAnyOptional non-negative weights, one per point (see sdvplot.hexbin): each bin's weight.
origintuple[float, float]The point a cell centre falls on (default (0.0, 0.0)): a hoop-centred lattice, origin = the basket's coordinates.
valueLiteral['count', 'weight']What the fill encodes: "count" (the default, the points in each cell) or "weight" (the sum of their weights).
fillfloat | NoneThe drawn cell's size as a fraction of the lattice cell, in (0, 1]: default 0.88 for squares (a gap, so they do not touch edge to edge) and 1.0 for hexagons (the tiled hexbin look).
min_countintCells with fewer points are not drawn (default 1, every cell). min_count=2 suits shot charts: single attempts are not drawn. sdvplot.hexbin / squarebin still return every cell.
**kwargsAnyPassed to PolyCollection: cmap, norm ("log" for ax.hexbin's bins="log"), edgecolors, linewidths, alpha, zorder, picker.

Returns​

Axes — The Axes drawn on.

Raises​

  • InputError: If the lattice options are not valid (see sdvplot.binner), value is not "count" or "weight".
  • UnsupportedTargetError: If target is not a matplotlib Axes, Figure or seaborn grid.
  • ValueError: If x, y and ids differ in length, or a Figure or grid has several Axes.

Example​

import matplotlib.pyplot as plt
import sdvplot
from sdvplot.matplotlib import add_bins

# three Brooklyn shots of 2025-26, legacy tenths of a foot (sportsdataverse-data nba_stats_shots)
fig, ax = plt.subplots()
add_bins(ax, [0, -1, -44], [0, 7, 252], shape="square", radius=10, equal_area=True, cmap="Blues")
fig.colorbar(ax.collections[-1], ax=ax, label="Shots")

See also​

add_headshots​

add_headshots(
target: Any,
x: Any,
y: Any,
players: Any,
*,
league: str,
height: float = 0.1,
alpha: float = 1,
zorder: float = 3,
id_system: str = 'espn',
transform: Any = None,
) -> Any

Draw each player's headshot centred on its (x, y) point of a matplotlib or seaborn plot.

Arguments​

NameTypeDescription
targetAnyA matplotlib Axes, a Figure with one Axes, or a seaborn grid with one Axes (or a JointGrid).
xAnyThe points' x positions, in data coordinates (read by position).
yAnyThe points' y positions, the same length as x.
playersAnyThe player id for each point.
leaguestrThe SDV league key, e.g. "nfl".
heightfloatThe headshot height as a fraction of the Axes height, in (0, 1].
alphafloatOpacity, 0 to 1.
zorderfloatmatplotlib drawing order.
id_systemstr"espn" (ESPN athlete ids), "gsis" (NFL) or "league" (the league's own player id: nfl gsis, NBA and WNBA Stats ids, MLBAM, NHL), as in headshot_url.
transformAnyThe coordinates x and y are in, when not the Axes' data: a Cartopy CRS such as ccrs.PlateCarree() (longitude/latitude, required on a GeoAxes) or a matplotlib Transform. A mark whose position falls outside the Axes is not drawn, whatever the transform.

Returns​

object — target itself, drawn on.

Raises​

  • InputError: (a ValueError) If height or alpha is out of range, league has no ESPN headshots, or id_system is not valid for league.
  • ValueError: If the inputs differ in length, the target has several Axes, or the target is a Cartopy GeoAxes and transform is None.
  • UnsupportedTargetError: (a TypeError) If target is not a matplotlib Axes, a Figure or a seaborn grid.
  • OfflineError: If a headshot, or with id_system="gsis" the nflverse player table, is neither cached nor downloadable (a DownloadError, also an OSError, for an HTTP error status).
  • UnsafeDownloadError: (an OSError) If a download is refused: larger than the byte cap, past the deadline, or redirected away from https.

Example​

import matplotlib.pyplot as plt
import sdvplot

fig, ax = plt.subplots()
sdvplot.add_headshots(ax, [0.5], [0.5], ["3139477"], league="nfl", height=0.2)

See also​

add_images​

add_images(
target: Any,
x: Any,
y: Any,
paths: Any,
*,
height: float = 0.1,
alpha: float = 1,
zorder: float = 3,
transform: Any = None,
) -> Any

Draw any image, by local path or URL, centred on each (x, y) point of a matplotlib or seaborn plot.

The image counterpart of add_logos, with the same sizing: height is a fraction of the Axes height, and each image keeps its aspect ratio. URLs are downloaded once and cached (like headshots); local files are read as they are. PNG, JPEG, GIF, WebP and the other formats Pillow reads work; SVG does not.

Arguments​

NameTypeDescription
targetAnyA matplotlib Axes, a Figure with one Axes, or a seaborn grid with one Axes (or a JointGrid).
xAnyThe points' x positions, in data coordinates (list, numpy array, or pandas/polars Series; read by position).
yAnyThe points' y positions, the same length as x.
pathsAnyThe image for each point (or one pathlib.Path for one point): a local path (str or pathlib.Path), a file:// URI or an https URL (http is refused). A null path draws nothing.
heightfloatThe image height as a fraction of the Axes height, in (0, 1].
alphafloatOpacity, 0 to 1.
zorderfloatmatplotlib drawing order (3 draws above lines and markers).
transformAnyThe coordinates x and y are in, when not the Axes' data: a Cartopy CRS (required on a GeoAxes) or a matplotlib Transform such as ax.transAxes.

Returns​

object — target itself, drawn on. Points whose image cannot be read (a missing file, a file that is not an image, a failed download) or whose x or y is missing are skipped, with one SdvplotWarning per reason.

Raises​

  • InputError: (a ValueError) If height or alpha is out of range.
  • ValueError: If x/y/paths differ in length, the target has several Axes, or the target is a Cartopy GeoAxes and transform is None. (An image that cannot be read or downloaded is skipped with a warning, not raised.)
  • UnsupportedTargetError: (a TypeError) If target is not a matplotlib Axes, a Figure or a seaborn grid.

Example​

import matplotlib.pyplot as plt
from sdvplot.matplotlib import add_images

fig, ax = plt.subplots()
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
add_images(ax, [3, 7], [5, 5], ["court.png", "https://www.python.org/static/img/python-logo.png"],
height=0.2)

See also​

add_logos​

add_logos(
target: Any,
x: Any,
y: Any,
teams: Any,
*,
league: str,
season: Any = None,
height: float = 0.1,
alpha: float = 1,
variant: str = 'default',
zorder: float = 3,
id_system: str = 'auto',
transform: Any = None,
) -> Any

Draw each team's logo centred on its (x, y) point of a matplotlib or seaborn plot.

Arguments​

NameTypeDescription
targetAnyA matplotlib Axes, a Figure with one Axes, or a seaborn grid with one Axes (or a JointGrid).
xAnyThe points' x positions, in data coordinates (list, numpy array, or pandas/polars Series; read by position).
yAnyThe points' y positions, the same length as x.
teamsAnyThe team for each point, in any id system resolve() understands.
leaguestrThe SDV league key, e.g. "nfl".
seasonAnyOne season, or one per point, to pick each team's mark for that era.
heightfloatThe logo height as a fraction of the Axes height, in (0, 1].
alphafloatOpacity, 0 to 1.
variantstr"default", "dark", or a named variant from marks().
zorderfloatmatplotlib drawing order (3 draws above lines and markers).
id_systemstrThe id system of teams; "auto" tries each in order.
transformAnyThe coordinates x and y are in, when not the Axes' data: a Cartopy CRS such as ccrs.PlateCarree() (longitude/latitude, required on a GeoAxes) or a matplotlib Transform. A mark whose position falls outside the Axes is not drawn, whatever the transform.

Returns​

object — target itself, drawn on.

Raises​

  • InputError: (a ValueError) If height or alpha is out of range, league, id_system or variant is unknown, or season is not a year or is outside the seasons sdvplot knows for the league.
  • ValueError: If x/y/teams differ in length, the target has several Axes, or the target is a Cartopy GeoAxes and transform is None.
  • UnsupportedTargetError: (a TypeError) If target is not a matplotlib Axes, a Figure or a seaborn grid.
  • OfflineError: If the logo manifest or a mark's image is neither cached nor downloadable (a DownloadError, also an OSError, when the CDN answers with an error status; an IntegrityError when it sends a file that does not match the manifest's sha256, or one PIL cannot decode).
  • UnsafeDownloadError: (an OSError) If a download is refused: larger than the byte cap, past the deadline, or redirected away from https.
  • UnsafeCachePathError: (a ValueError) If the manifest's sha256 or extension for a mark would put the file outside the cache directory.
  • OptionalDependencyError: If a mark is an SVG and the svg extra is not installed.

Example​

import matplotlib.pyplot as plt
import sdvplot

fig, ax = plt.subplots()
ax.set_xlim(0, 30)
ax.set_ylim(-10, 0)
sdvplot.add_logos(ax, [10, 20], [-3, -7], ["KC", "BUF"], league="nfl", height=0.15)

# On a Cartopy map, at longitude/latitude:
# import cartopy.crs as ccrs
# ax = plt.axes(projection=ccrs.Robinson())
# ax.set_global()
# sdvplot.add_logos(ax, [-94.48], [39.05], ["KC"], league="nfl", transform=ccrs.PlateCarree())

See also​

add_wordmarks​

add_wordmarks(
target: Any,
x: Any,
y: Any,
teams: Any,
*,
league: str,
season: Any = None,
height: float = 0.1,
alpha: float = 1,
variant: str = 'default',
zorder: float = 3,
id_system: str = 'auto',
transform: Any = None,
) -> Any

Draw each team's wordmark centred on its (x, y) point of a matplotlib or seaborn plot.

Arguments​

NameTypeDescription
targetAnyA matplotlib Axes, a Figure with one Axes, or a seaborn grid with one Axes (or a JointGrid).
xAnyThe points' x positions, in data coordinates (read by position).
yAnyThe points' y positions, the same length as x.
teamsAnyThe team for each point, in any id system resolve() understands.
leaguestrThe SDV league key, e.g. "nfl".
seasonAnyOne season, or one per point.
heightfloatThe wordmark height as a fraction of the Axes height, in (0, 1].
alphafloatOpacity, 0 to 1.
variantstr"default", "dark", or a named variant from marks().
zorderfloatmatplotlib drawing order.
id_systemstrThe id system of teams; "auto" tries each in order.
transformAnyThe coordinates x and y are in, when not the Axes' data: a Cartopy CRS such as ccrs.PlateCarree() (longitude/latitude, required on a GeoAxes) or a matplotlib Transform. A mark whose position falls outside the Axes is not drawn, whatever the transform.

Returns​

object — target itself, drawn on.

Raises​

  • InputError: (a ValueError) If height or alpha is out of range, league, id_system or variant is unknown, or season is not a year or is outside the seasons sdvplot knows for the league.
  • ValueError: If the inputs differ in length, the target has several Axes, or the target is a Cartopy GeoAxes and transform is None.
  • UnsupportedTargetError: (a TypeError) If target is not a matplotlib Axes, a Figure or a seaborn grid.
  • OfflineError: If the logo manifest or a mark's image is neither cached nor downloadable (a DownloadError, also an OSError, when the CDN answers with an error status; an IntegrityError when it sends a file that does not match the manifest's sha256, or one PIL cannot decode).
  • UnsafeDownloadError: (an OSError) If a download is refused: larger than the byte cap, past the deadline, or redirected away from https.
  • UnsafeCachePathError: (a ValueError) If the manifest's sha256 or extension for a mark would put the file outside the cache directory.
  • OptionalDependencyError: If a mark is an SVG and the svg extra is not installed.

Example​

import matplotlib.pyplot as plt
import sdvplot

fig, ax = plt.subplots()
sdvplot.add_wordmarks(ax, [0.5], [0.5], ["KC"], league="nfl", height=0.1)

See also​

axis_logos​

axis_logos(
target: Any,
axis: str,
*,
league: str,
season: Any = None,
height: float = 0.1,
variant: str = 'default',
mark_type: Literal['logo', 'wordmark', 'headshot'] = 'logo',
id_system: str = 'auto',
) -> Any

Replace a team axis' tick labels with the teams' logos (or wordmarks), or a player axis' with headshots.

Reads the axis' ticks and labels when called, so call it after setting the categories and limits. Labels that are not teams (or, with mark_type="headshot", not player ids with a headshot) stay as text, with one SdvplotWarning.

Arguments​

NameTypeDescription
targetAnyA matplotlib Axes, a Figure with one Axes, or a seaborn grid with one Axes.
axisstr"x" or "y".
leaguestrThe SDV league key, e.g. "nfl".
seasonAnyOne season for every label.
heightfloatThe image height as a fraction of the Axes height, in (0, 1].
variantstr"default", "dark", or a named variant from marks().
mark_typeLiteral['logo', 'wordmark', 'headshot']"logo", "wordmark" or "headshot". With "headshot" the labels are player ids (id_system "espn", "gsis" or "league" as in headshot_url, "auto" meaning "espn"; season is ignored), drawn at their own aspect.
id_systemstrThe id system of the labels; "auto" tries each in order.

Returns​

object — target itself, drawn on.

Raises​

  • InputError: (a ValueError) If height is out of range, league, id_system, mark_type or variant is unknown, season is not a year or is outside the seasons sdvplot knows for the league, or league has no ESPN headshots for mark_type="headshot".
  • ValueError: If axis is not "x"/"y", or the target has several Axes.
  • UnsupportedTargetError: (a TypeError) If target is not a matplotlib Axes, a Figure or a seaborn grid.
  • OfflineError: If the logo manifest, a mark's image or a headshot is neither cached nor downloadable (a DownloadError, also an OSError, when the CDN answers with an error status; an IntegrityError when it sends a file that does not match the manifest's sha256, or one PIL cannot decode).
  • UnsafeDownloadError: (an OSError) If a download is refused: larger than the byte cap, past the deadline, or redirected away from https.
  • UnsafeCachePathError: (a ValueError) If the manifest's sha256 or extension for a mark would put the file outside the cache directory.
  • OptionalDependencyError: If a mark is an SVG and the svg extra is not installed.

Example​

import matplotlib.pyplot as plt
import sdvplot

fig, ax = plt.subplots()
ax.bar(["KC", "BUF", "BAL"], [12, 10, 9])
sdvplot.axis_logos(ax, "x", league="nfl", height=0.08)

# player headshots as the labels of a leaderboard (ESPN athlete ids)
fig, ax = plt.subplots()
ax.barh(["3139477", "3918298"], [0.31, 0.27])
sdvplot.axis_logos(ax, "y", league="nfl", mark_type="headshot", height=0.2)

See also​

team_tiers​

team_tiers(
data: Any,
league: str,
*,
title: str | None = None,
subtitle: str | None = 'created with the #sdvplot Tiermaker',
caption: str | None = None,
tier_desc: dict[Any, str] | None = None,
presort: bool = False,
alpha: float = 0.8,
height: float | None = None,
no_line_below_tier: Any = None,
devel: bool = False,
theme: Literal['dark', 'light'] = 'dark',
variant: str = 'auto',
) -> matplotlib.figure.Figure

A tier list: each team's logo in its tier's row, tier 1 on top, on a dark (sdvplotR) or light theme.

Arguments​

NameTypeDescription
dataAnyA pandas or polars DataFrame with tier_no (1 is the top tier) and team (any id system resolve() understands), and optionally tier_rank, the position within the tier; without it, teams keep their order in data.
leaguestrThe SDV league key, e.g. "nfl".
titlestr | NoneThe title; None gives "{LEAGUE} Team Tiers", "" none.
subtitlestr | NoneThe subtitle; None or "" for none.
captionstr | NoneThe caption, bottom right; None for none.
tier_descdict[Any, str] | NoneEach tier's label, keyed by tier number; None gives sdvplotR's (1 "Elite" ... 5 "What are they doing?"). Labels wrap at 15 characters; a tier without one gets none.
presortboolSort teams alphabetically within each tier (ignores tier_rank).
alphafloatLogo opacity, 0 to 1.
heightfloat | NoneLogo height as a fraction of the panel height; None gives 0.1, about the largest height at which 32 logos in 5 tiers (7, 7, 6, 6, 6) neither overlap nor leave the panel at the default 6.4 x 4.8 in figure.
no_line_below_tierAnyA tier number, or several, with no separator line below.
develboolDraw each team as text instead of its logo (fast, and needs no download).
themeLiteral['dark', 'light']"dark" (sdvplotR's: a near-black background) or "light" (white).
variantstrThe logo variant: "auto" (the default) draws the archive's "dark" variant, a mark made for dark backgrounds, on the dark theme and "default" on the light one; a team with no dark mark draws its default one, with no warning. Any other value ("default", "dark" or a named variant from marks()) is drawn on either theme, as add_logos draws it: variant="default" keeps the default logos on the dark theme, as sdvplotR and sdvplot 0.1.0 draw them.

Returns​

matplotlib.figure.Figure — A new figure with one Axes; a team that does not resolve is skipped with one SdvplotWarning, keeping its slot.

Raises​

  • TypeError: If data is not a DataFrame, or tier_no/tier_rank hold non-numbers.
  • InputError: (a ValueError) If height/alpha is out of range, or league is unknown; unless devel=True, if variant is a name no mark in the archive has.
  • ValueError: If data lacks tier_no or team, has no row with a tier, or theme is not "dark" or "light".
  • OfflineError: Unless devel=True, if the logo manifest or a mark's image is neither cached nor downloadable (a DownloadError, also an OSError, when the CDN answers with an error status; an IntegrityError when it sends a file that does not match the manifest's sha256, or one PIL cannot decode).
  • UnsafeDownloadError: (an OSError) Unless devel=True, if a download is refused: larger than the byte cap, past the deadline, or redirected away from https.
  • UnsafeCachePathError: (a ValueError) Unless devel=True, if the manifest's sha256 or extension for a mark would put the file outside the cache directory.
  • OptionalDependencyError: Unless devel=True, if a logo is an SVG and the svg extra is not installed.

Example​

import pandas as pd
from sdvplot.matplotlib import team_tiers

df = pd.DataFrame({"tier_no": [1, 1, 2, 3], "team": ["KC", "BUF", "BAL", "NYJ"]})
fig = team_tiers(df, "nfl")

# Draft it as text first, then add logos:
fig = team_tiers(df, "nfl", devel=True, no_line_below_tier=1)

# A white background:
fig = team_tiers(df, "cfb", theme="light")

# The default logos on the dark background, as sdvplotR draws them:
fig = team_tiers(df, "nfl", variant="default")

See also​

title_image​

title_image(
target: Any,
image: Any,
title: str = '',
*,
league: str | None = None,
season: Any = None,
side: str = 'left',
height: float = 15,
**text_kw: Any,
) -> Any

Set the plot title and draw an image (a team logo, or any image) beside it.

The title and the image are aligned together, like the image inside sdvplotR's title: a centred title centres the pair, a left-aligned one starts with the image.

Arguments​

NameTypeDescription
targetAnyA matplotlib Axes (sets its title), a Figure (sets its suptitle), or a seaborn grid with one Axes.
imageAnyA team, in any id system resolve() understands, when league is given; otherwise an image URL (https; http is refused) or a local file path.
titlestrThe title text.
leaguestr | NoneThe SDV league key, e.g. "nfl"; None reads image as a URL or path.
seasonAnyOne season, to pick the team's logo for that era.
sidestr"left" or "right" of the title text.
heightfloatThe image height in points (1/72 inch), at any dpi. The title keeps its own line height, so an image much taller than the text needs room: pad= on an Axes title, y= on a Figure's suptitle.
**text_kwAnyPassed to Axes.set_title (loc, fontsize, pad, ...) or Figure.suptitle.

Returns​

object — target itself, titled. Calling it again on the same title replaces the image. An image by URL or path that cannot be read gives one SdvplotWarning and the title without it.

Raises​

  • TypeError: If league is given and image is not one team.
  • InputError: (a ValueError) If height is not a number of points of at least 1, or league is given and it is unknown or season is not a year or is outside the seasons sdvplot knows for the league.
  • ValueError: If side is not "left"/"right", or the target has several Axes.
  • UnsupportedTargetError: (a TypeError) If target is not a matplotlib Axes, a Figure or a seaborn grid.
  • OfflineError: If league is given and the team's logo (or the logo manifest) is neither cached nor downloadable (a DownloadError, also an OSError, when the CDN answers with an error status; an IntegrityError when it sends a file that does not match the manifest's sha256, or one PIL cannot decode). An image by URL or path that cannot be read is skipped with a warning instead.
  • UnsafeDownloadError: (an OSError) If league is given and a download is refused: larger than the byte cap, past the deadline, or redirected away from https.
  • UnsafeCachePathError: (a ValueError) If league is given and the manifest's sha256 or extension for the logo would put the file outside the cache directory.
  • OptionalDependencyError: If league is given, the logo is an SVG and the svg extra is not installed.

Example​

import matplotlib.pyplot as plt
from sdvplot.matplotlib import title_image

fig, ax = plt.subplots()
ax.plot([1, 2, 3], [3, 1, 2])
title_image(ax, "KC", "Kansas City Chiefs Analysis", league="nfl", height=20)

# A Figure's suptitle, the image on the right:
title_image(fig, "https://example.com/banner.png", "Week 1", side="right")

See also​