Guide
NBA shot chart in Python with matplotlib
Short answer: call DunkAPI's get_shot_chart with include_shots true, then plot each shot's x and y over a half court drawn with matplotlib patches. We rendered Stephen Curry's 2025-26 chart locally: 799 attempts, 374 made, and 56.4 percent of them above-the-break threes.
A shot chart is a description of where a player shot and what happened. This guide covers drawing it and reading it. It does not suggest any wager.
What the endpoint returns
get_shot_chart costs 10 credits per call. Given a player_id, a team or a game_id, plus a season, it returns two things. The first is a zone table, one row per area of the court with attempts, makes, percentage, points per shot and our expected points per shot. The second, only when you set include_shots to true, is a list of every field goal attempt with x, y, made and pts, up to 3,000 shots.
Seasons are named for the year they end, so 2026 is the 2025-26 season. The coordinates are in feet. The x value runs from 0 to 50 across the court. The y value is the distance out from the basket, which is at (25, 0). The response note says the same. Our player returned x from 1 to 49 and y from -3 to 40, so a few shots came from behind the basket line and the farthest came from 40 feet out.
Pass team with opponent set to true to get the shots a team's opponents took, which is a defence chart. Pass game_id for one game. Find a player's id with search_players, which costs 1 credit. For Curry it returned id 3975.
Why the frame is convenient
Many shot data sets put the origin at a corner of the court and make you convert. Here the basket is the origin of y, which makes distance a one-liner: the straight-line distance from a shot to the rim is ((x - 25) ** 2 + y ** 2) ** 0.5. It also makes the drawing code short, because every court landmark is a small number in the same units.
The landmarks you need for a half court, measured in this frame, are:
- The rim is a circle of radius 0.75 centred at (25, 0).
- The backboard is a line 6 feet wide, 1.25 feet behind the basket centre.
- The baseline sits 5.25 feet behind the basket, at y = -5.25.
- The lane is 16 feet wide, from x = 17 to 33, running from the baseline to the free-throw line at y = 15.
- The free-throw circle has a 6 foot radius, centred on the free-throw line.
- The restricted area is an arc of radius 4 feet.
- The three-point line is a 23.75 foot arc from the basket, joined by straight lines at x = 3 and x = 47 in the corners. The arc meets the corner lines at y = 8.94, since 23.75 squared minus 22 squared is about 80, and the square root is 8.94.
Those are standard court dimensions, not values from the API.
Step 1: fetch and draw
The script searches for the player, requests the chart, and draws it. Set DUNKAPI_API_KEY first. The court function takes an axis and adds the patches. Made shots are filled blue circles, missed shots are red crosses, and both are partly transparent so that clusters show up as darker areas instead of hiding each other.
import json, os, urllib.request
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.patches import Arc, Circle, Rectangle
KEY = os.environ["DUNKAPI_API_KEY"]
def post(tool, body):
req = urllib.request.Request(f"https://mcp.dunkapi.com/v1/{tool}", data=json.dumps(body).encode(),
headers={"Content-Type": "application/json", "x-api-key": KEY})
with urllib.request.urlopen(req, timeout=90) as r:
return json.load(r)["data"]
player = post("search_players", {"name": "stephen curry", "limit": 1})["players"][0]
chart = post("get_shot_chart", {"player_id": player["player_id"], "season": 2026, "include_shots": True})
shots = chart["shots"]
print(player["name"], len(shots), "shots", sum(s["made"] for s in shots), "made")
def court(ax):
"""Half court in the API frame: x 0-50 across, y feet out from the basket at (25, 0)."""
kw = dict(color="#444", lw=1.2, fill=False)
ax.add_patch(Circle((25, 0), 0.75, **kw)) # rim
ax.plot([22, 28], [-1.25, -1.25], color="#444", lw=2) # backboard
ax.add_patch(Rectangle((17, -5.25), 16, 20.25, **kw)) # lane to the free-throw line
ax.add_patch(Arc((25, 15), 12, 12, theta1=0, theta2=180, **kw)) # free-throw circle
ax.add_patch(Arc((25, 0), 8, 8, theta1=0, theta2=180, **kw)) # restricted area
ax.plot([3, 3], [-5.25, 8.94], color="#444", lw=1.2) # corner threes
ax.plot([47, 47], [-5.25, 8.94], color="#444", lw=1.2)
ax.add_patch(Arc((25, 0), 47.5, 47.5, theta1=22.2, theta2=157.8, **kw)) # 23.75 ft arc
ax.add_patch(Rectangle((0, -5.25), 50, 47.25, **kw)) # baseline and sidelines
ax.set_xlim(-1, 51); ax.set_ylim(-6.5, 36); ax.set_aspect("equal"); ax.axis("off")
fig, ax = plt.subplots(figsize=(6, 6))
court(ax)
for made, color, marker, label in [(False, "#c0392b", "x", "missed"), (True, "#1f77b4", "o", "made")]:
pts = [s for s in shots if s["made"] == made]
ax.scatter([s["x"] for s in pts], [s["y"] for s in pts], s=22, c=color, marker=marker,
alpha=0.65, linewidths=1, label=f"{label} ({len(pts)})",
facecolors=color if marker == "x" else "none")
ax.legend(loc="upper right", frameon=False)
ax.set_title(f"{player['name']}, 2025-26 regular season", fontsize=11)
fig.savefig("curry_shot_chart.png", dpi=150, bbox_inches="tight")
print("saved curry_shot_chart.png")We ran this script and wrote curry_shot_chart.png with matplotlib 3.9.4 and the Agg backend, a 6 by 6 inch figure at 150 dpi. Then we opened the image and checked it. The court lines align: the arc meets the corner lines, the lane and free-throw circle are square to the basket, and the restricted-area arc surrounds a dense clump of blue circles under the rim. The legend reported 374 made and 425 missed. The arc is crowded with both markers. The area between the lane and the arc is sparse.
If your own image looks wrong, the usual cause is the axis. Set the aspect to equal so a foot is the same length in both directions, turn the axis off, and keep ylim from about -6.5 to 36 so the half court fits. Do not invert the y axis. The basket is at the bottom of the picture by design, which is how a half court is usually shown.
Step 2: read the zone table
The picture shows where. The zone table says how well, and compares each zone with what our expected points model says a typical shot from that spot is worth. This second script fetches the same chart and builds the table.
import json, os, urllib.request
import pandas as pd
KEY = os.environ["DUNKAPI_API_KEY"]
def post(tool, body):
req = urllib.request.Request(f"https://mcp.dunkapi.com/v1/{tool}", data=json.dumps(body).encode(),
headers={"Content-Type": "application/json", "x-api-key": KEY})
with urllib.request.urlopen(req, timeout=90) as r:
return json.load(r)["data"]
chart = post("get_shot_chart", {"player_id": "3975", "season": 2026, "include_shots": True})
zones = pd.DataFrame(chart["zones"]).set_index("zone")
fg = zones.drop(index="free_throw", errors="ignore") # free throws are a zone row, not a field goal
fg = fg[["attempts", "made", "pct", "points_per_shot", "expected_points_per_shot"]]
fg["share"] = (fg.attempts / fg.attempts.sum()).round(3)
fg["pps_minus_expected"] = (fg.points_per_shot - fg.expected_points_per_shot).round(3)
print(fg.round(3))
shots = pd.DataFrame(chart["shots"])
print(len(shots), "shots,", int(shots.made.sum()), "made, FG%", round(shots.made.mean(), 3))
# The zone table and the raw points agree: recompute attempts from the shot rows.
print("rows with 3 points:", int((shots.pts == 3).sum()), "| zone 3PA:", int(fg.loc[["corner_3", "above_break_3"]].attempts.sum()))
# A coarse own-grid check: attempts in 10 ft distance rings from the basket at (25, 0).
d = ((shots.x - 25) ** 2 + shots.y ** 2) ** 0.5
rings = pd.cut(d, [0, 5, 10, 16, 22, 26, 60])
print(shots.groupby(rings, observed=True).made.agg(["size", "mean"]).round(3))| Zone | Attempts | Made | FG% | Points per shot | Expected points per shot | Share |
|---|---|---|---|---|---|---|
| Restricted area | 109 | 76 | 0.697 | 1.394 | 1.244 | 0.136 |
| Paint | 115 | 61 | 0.530 | 1.061 | 0.823 | 0.144 |
| Mid-range | 91 | 47 | 0.516 | 1.033 | 0.814 | 0.114 |
| Corner three | 33 | 18 | 0.545 | 1.636 | 1.146 | 0.041 |
| Above-the-break three | 451 | 172 | 0.381 | 1.144 | 1.005 | 0.564 |
Free throws are returned as a sixth zone row, 221 attempts and 204 made at 0.923, and the script drops them because they are not field goal attempts. The five field goal rows sum to 799, the same as field_goal_attempts and the length of the shot list. As a second check, 484 shots in the list are worth three points and the two three-point zones add to 484 as well.
Two lines of reading help. The first is the diet: more than half of this player's attempts are above-the-break threes, and only 4.1 percent are corner threes. The second is finishing against expectation. In every zone his points per shot ran above the model's expected value for a typical shot, by 0.139 above the break, 0.150 in the restricted area, 0.219 in the mid-range, 0.238 in the paint and 0.490 on the 33 corner threes. That last number rests on 33 attempts, where a few makes more or fewer would move it a lot. The 451 above-the-break attempts are the most reliable line in the table.
Rings as a second view
A zone table is coarse, so the script also bins shots into distance rings from the rim. The made rate falls from 0.681 within 5 feet, to 0.545 from 5 to 10 feet, then 0.426 from 10 to 16 feet. It rises to 0.562 from 16 to 22 feet, where the sample is only 48 shots, and drops to 0.423 from 22 to 26 feet and 0.379 beyond 26. The non-monotone rise between 10 and 22 feet shows that a shot's location is not the only thing that matters. Forty-eight shots is too few to treat the 0.562 as a trait.
Variations worth trying
Replace the scatter with a hexbin of attempts, coloured by the made rate in each hexagon, once you have a few thousand shots. A single player's 799 attempts are better as a scatter. Make a defence chart by passing team and opponent true, then compare it with the offence chart on the same axes. Draw two seasons side by side to see a change in shot profile. Colour by made and size by nothing, which keeps the chart honest, since a size scale invites readers to compare areas.
On accessibility, a red and blue pair works for most viewers, and the cross and circle shapes carry the difference without colour. Keep alpha near 0.65 so overlapping shots still show density.
Limits
- One player, one season. The zone numbers are for 799 attempts. A different year or a smaller role gives a thinner table.
- Small cells. The corner three has 33 attempts and the mid-range 91. Differences in those rows can vanish with a few more shots.
- Expected points is a league model. It does not know who was guarding, how much time was left or whether the shot was a catch-and-shoot. A positive gap is not proof of skill.
- Credits. The chart is 10 credits a call. The key used for this guide is low on credits, so the script was run three times in total, which is 30 credits plus a 1 credit search.
- College leagues carry shot locations but no expected points yet. The zone columns for them are missing.
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.