Starter project

NBA shot chart dashboard with Streamlit

This Streamlit app lets you type an NBA player's name, pick a season, and see every shot he took drawn on a half court, with made and missed shots marked and a zone table of attempts, makes and expected points. Three Python files, one API call per chart at 10 credits, cached for an hour.

What you will build

A one-page dashboard. At the top is a text box for a player's name. Below it, a dropdown lists the matching players, with team and last season, and a number box sets the season. The page then draws a half court with the three-point line, the paint, the free throw circle and the restricted area, and plots each shot as a green circle if it went in or a red cross if it missed. Under the chart is a table with one row per zone.

Sample table from a real run (Jalen Brunson, 2026-27 season, 461 field goal attempts):

zone             attempts  made  pct    points_per_shot  expected_points_per_shot
restricted_area  75        41    0.547  1.093            1.281
paint            110       46    0.418  0.836            0.885
midrange         120       51    0.425  0.850            0.859
corner_3         15        7     0.467  1.400            1.145
above_break_3    141       51    0.362  1.085            1.071
free_throw       132       107   0.811  0.811            (none)

The chart for that player shows a dense cluster under the basket, a ring of misses and makes through the paint and mid-range, and a wide band of attempts just inside and outside the three-point arc, with a thin column of attempts in each corner. The legend in the upper right gives the made and missed counts, here 196 and 265.

Prerequisites

  • Python 3.9 or newer (the run below used 3.9.6).
  • A DunkAPI key. One chart costs 10 credits and a name search costs 1.
  • A browser to view the app locally.

The project

shot-chart/
  requirements.txt
  data.py     API calls, cached for an hour
  court.py    half-court drawing and the shot scatter
  app.py      the Streamlit page

requirements.txt

streamlit>=1.35
matplotlib>=3.8
requests>=2.31
pandas>=2.0

data.py

"""DunkAPI calls for the dashboard. The key comes from the DUNKAPI_KEY environment variable."""
import os
from typing import Optional

import requests
import streamlit as st

BASE = os.environ.get("DUNKAPI_BASE", "https://mcp.dunkapi.com/v1")


def call(tool: str, **params) -> dict:
    resp = requests.post(
        f"{BASE}/{tool}",
        headers={"x-api-key": os.environ["DUNKAPI_KEY"], "Content-Type": "application/json"},
        json=params,
        timeout=60,
    )
    resp.raise_for_status()
    body = resp.json()
    return body.get("data", body)  # responses may arrive wrapped as {"data": ...}


@st.cache_data(ttl=3600, show_spinner=False)
def find_players(name: str) -> list[dict]:
    return call("search_players", name=name, limit=8)["players"]          # 1 credit


@st.cache_data(ttl=3600, show_spinner=False)
def shot_chart(player_id: str, season: Optional[int]) -> dict:
    params = {"player_id": player_id, "include_shots": True}              # 10 credits
    if season:
        params["season"] = season
    return call("get_shot_chart", **params)

court.py

"""Draw a half court in feet. The basket is at (25, 0); x runs 0-50 across, y runs up the court."""
import matplotlib.pyplot as plt
from matplotlib.patches import Arc, Circle, Rectangle


def draw_court(ax):
    line = dict(color="#444", linewidth=1.2, fill=False)
    ax.add_patch(Circle((25, 0), 0.75, **line))                         # rim
    ax.plot([22, 28], [-1.5, -1.5], color="#444", linewidth=2)          # backboard
    ax.add_patch(Rectangle((17, -1.5), 16, 20.5, **line))               # paint
    ax.add_patch(Arc((25, 19), 12, 12, theta1=0, theta2=180, color="#444", linewidth=1.2))  # free throw
    ax.add_patch(Arc((25, 0), 8, 8, theta1=0, theta2=180, color="#444", linewidth=1.2))     # restricted area
    ax.plot([3, 3], [-1.5, 14], color="#444", linewidth=1.2)            # corner three lines
    ax.plot([47, 47], [-1.5, 14], color="#444", linewidth=1.2)
    ax.add_patch(Arc((25, 0), 47.5, 47.5, theta1=22, theta2=158, color="#444", linewidth=1.2))  # three-point arc
    ax.set_xlim(0, 50)
    ax.set_ylim(-3, 40)
    ax.set_aspect("equal")
    ax.axis("off")


def plot_shots(shots: list[dict], title: str):
    fig, ax = plt.subplots(figsize=(6, 5.6))
    draw_court(ax)
    made = [s for s in shots if s["made"]]
    miss = [s for s in shots if not s["made"]]
    ax.scatter([s["x"] for s in miss], [s["y"] for s in miss], s=14, marker="x",
               color="#c0392b", alpha=0.45, label=f"Missed ({len(miss)})")
    ax.scatter([s["x"] for s in made], [s["y"] for s in made], s=14, marker="o",
               color="#1e8449", alpha=0.6, label=f"Made ({len(made)})")
    ax.set_title(title)
    ax.legend(loc="upper right", frameon=False, fontsize=8)
    return fig

app.py

import pandas as pd
import streamlit as st
from court import plot_shots
from data import find_players, shot_chart

st.set_page_config(page_title="NBA shot chart", layout="centered")
st.title("NBA shot chart")

name = st.text_input("Player name", value="Brunson")
players = find_players(name) if len(name) >= 3 else []
if not players:
    st.info("Type at least three letters of a player's name.")
    st.stop()

labels = {f'{p["name"]} ({p["team"]}, last season {p["last_season"]})': p for p in players}
player = labels[st.selectbox("Player", list(labels))]
season = st.number_input("Season (ends in this year, 2026 = 2025-26)", 2005, 2027, int(player["last_season"]))

try:
    chart = shot_chart(player["player_id"], int(season))
except Exception as e:  # for example a player with no shots in that season
    st.error(f"No shot chart for that player and season ({e}).")
    st.stop()

shots = chart.get("shots", [])
st.pyplot(plot_shots(shots, f'{player["name"]}, {season}: {chart["field_goal_attempts"]} attempts'))

zones = pd.DataFrame(chart["zones"])
st.subheader("By zone")
st.dataframe(zones, hide_index=True)
if chart.get("shots_note"):
    st.caption(chart["shots_note"])

How to run it

python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
export DUNKAPI_KEY="your-key-here"
streamlit run app.py

Streamlit opens the app at http://localhost:8501. Type a name of three letters or more, choose the player and set the season. Seasons are named by the year they end, so 2026 means 2025-26.

How it works

The API layer. data.py makes two calls. search_players takes a name and returns ids, teams and the last season each player appeared in. get_shot_chart takes a player_id, a season and include_shots, and returns the zone summary plus every shot as an x, y, made flag and point value. Both wrap results in a data envelope, which the helper unwraps. The st.cache_data decorator keeps each answer for an hour, keyed on the arguments, so reloading the page or moving a widget does not spend credits again.

The court. court.py draws the lines from the official dimensions in feet, so shots plot without any conversion. The basket is at (25, 0). The paint is 16 feet wide and 19 feet from the baseline, the free throw circle has a six foot radius, the restricted area an arc of four feet, and the three-point line is a 23.75 foot arc joined to straight corner lines 3 feet from each sideline. The y-axis is set to run from slightly behind the basket to 40 feet, which clips a small number of heaves from past half court. Matplotlib's Arc and Circle patches do most of the work.

The scatter. Made shots and misses are drawn in separate layers with different markers, not just different colors, so the chart still reads for color-blind viewers. Low opacity lets dense areas show through. The title carries the attempt count and the legend shows the made and missed counts.

The page. app.py is a straight script, which is how Streamlit works: each interaction reruns it from the top. It waits for at least three letters before searching, stops with a message when nothing matches, and wraps the chart call in a try block, in case the API returns an error for a player and season with no shots. The season box defaults to each player's last season.

The zone table. The API summarizes shots by zone: restricted area, paint, mid-range, corner three, above-the-break three, and free throws. Each row has attempts, makes, the shooting percentage, points per shot, and the model's expected points per shot. Expected points exist for NBA and WNBA shots only, so that column is empty for free throws. The zone table counts free throws, but the shot list and the attempt total do not, which is why the table has 593 attempts and the chart 461.

Ways to extend it

  1. Add a heat map. Replace the scatter with a hexbin of the shots colored by made rate or points per shot minus expected points. Hexbins read better than dots once a player has more than a few hundred shots.
  2. Compare two players. Add a second search box and draw both charts side by side with st.columns. Cache keeps the cost to one call per player and season.
  3. Add team and defense views. get_shot_chart also accepts a team, and with opponent set to true it returns the shots a team's opponents took. Draw the same chart for a defense.
  4. Filter by game or season type. The tool takes a game_id and a season_type, so you can add a selector for the regular season versus the postseason, or draw a single game.

Limits and when not to use this

  • One call per chart. Each new player or season costs 10 credits. Cache lasts only while the Streamlit process lives, so a restart spends credits again. Add a disk cache if you share the app.
  • The key lives on whoever runs the app. This is a local or team tool. If you deploy it publicly, anyone who opens the page spends your credits, so put it behind a login or a rate limit.
  • Shot cap. A call returns up to 3,000 shots. That is enough for one player in one season, but a whole team across seasons can exceed it.
  • Model values. Expected points come from a model. They help compare shot quality, and they are not a record of what happened.
  • Streamlit reruns the script. Fine for a few users, but not a design for hundreds of concurrent visitors. For a public page, build a server-rendered route that caches by player and season.
  • Terms. Using the data to build charts for your users is fine. Redistributing the raw shots as a dataset or feed is not. See the DunkAPI documentation for the full terms.

FAQ

What are the court coordinates? Shots use feet. The x value runs 0 to 50 across the court, y runs up the court from the basket, and the basket sits at (25, 0). That is why the drawing code places the rim at (25, 0) and needs no conversion.

What is expected points per shot? It is DunkAPI's model value of a shot from its location and type, fitted on every shot in league history. Comparing a player's points per shot with the expected figure shows where he shoots above or below the typical result.

How many shots can one chart show? Up to 3,000 shots per call, which covers a full regular season and playoffs for any player. Pass a season to keep the chart to one year, and a team id instead of a player to see a whole team.

Live from the API

Free to embed on your own site, with no key needed. Get the embed code.

Get a free key Or download whole seasons as Parquet

Checked against the live API on 2026-12-06. Questions: hello@sportsdatahq.com.