Skip to content

Guides

NBA shot chart with expected points in Python

Pull every located shot a player took in a season, draw the court with matplotlib, and compare points per shot with expected points per shot in each zone.

Every script run against the live API on December 4, 2026. One full run: 33 credits.

This tutorial draws an NBA shot chart from a season of located shots and then asks a second question the chart cannot answer: how good were the shots, and how well were they made. Each zone comes back with the points the player actually scored per shot and the points per shot our model expected from where and how the shots were taken.

The example is Shai Gilgeous-Alexander's 2025-26 regular season: 1,322 field goal attempts, every one with a court location. The same calls work for any NBA or WNBA player, a team or one game. One full run costs 33 credits: 3 player searches at 1 credit and 3 shot charts at 10 credits.

1. Install the client and set your key

The client has no required dependencies. This tutorial uses pandas for the tables and matplotlib for the court. The client reads your key from DUNKAPI_API_KEY.

pip install "dunkapi[pandas]" matplotlib
export DUNKAPI_API_KEY=your_key_here

2. Pull the season's shots and the zone table

search_players finds the player id. get_shot_chart returns a table by zone (restricted area, paint, midrange, corner three, above-the-break three and free throws) and, with include_shots=True, every located shot. Seasons are named by the year they end, so 2026 is 2025-26. The script drops free throws, which are not among the located shots and carry no expected value, and works out how many points each zone's shots scored above the model's expectation: (points per shot minus expected points per shot) times attempts.

import json
import pandas as pd
from dunkapi import Client

client = Client()  # reads DUNKAPI_API_KEY

player = client.search_players("Gilgeous-Alexander", limit=1)["players"][0]
chart = client.get_shot_chart(player_id=player["player_id"], season=2026, include_shots=True)
with open("sga_shot_chart_2026.json", "w") as f:
    json.dump(chart, f)

zones = pd.DataFrame(chart["zones"])
zones = zones[zones["zone"] != "free_throw"].copy()  # field goals only
zones["above_expected"] = (zones["points_per_shot"] - zones["expected_points_per_shot"]) * zones["attempts"]

print(player["name"], player["player_id"], "|", chart["field_goal_attempts"], "field goal attempts,", len(chart["shots"]), "located")
cols = ["zone", "attempts", "made", "pct", "points_per_shot", "expected_points_per_shot", "above_expected"]
print(zones[cols].round(3).to_string(index=False))
print("points above expected:", round(zones["above_expected"].sum(), 1))
print("credits left:", client.last_credits_remaining)

Output

Shai Gilgeous-Alexander 4278073 | 1322 field goal attempts, 1322 located
           zone  attempts  made   pct  points_per_shot  expected_points_per_shot  above_expected
restricted_area       344   246 0.715            1.430                     1.298          45.408
          paint       348   192 0.552            1.103                     0.884          76.212
       midrange       332   178 0.536            1.072                     0.867          68.060
       corner_3        16     5 0.313            0.938                     1.150          -3.392
  above_break_3       282   110 0.390            1.170                     1.067          29.046
points above expected: 215.3
credits left: 3547

The last line is the credit balance of the key that ran it; yours will differ. Every shot has a location, so all 1,322 are plotted below. expected_points_per_shot is our model's value of a shot from where it was taken and what kind of shot it was, averaged over the player's attempts in the zone.

3. Shot quality against shot making, by zone

import json
import matplotlib.pyplot as plt
import pandas as pd

chart = json.load(open("sga_shot_chart_2026.json"))
zones = pd.DataFrame(chart["zones"])
zones = zones[zones["zone"] != "free_throw"].set_index("zone")
ax = zones[["points_per_shot", "expected_points_per_shot"]].plot.bar(figsize=(9, 4), rot=0)
ax.set_ylabel("Points per shot")
ax.legend(["Scored", "Expected"])
plt.tight_layout()
plt.savefig("sga_zones.png", dpi=150)
Shai Gilgeous-Alexander, points per shot by zone, 2025-26 regular season
  • Scored
  • Expected
0.000.501.001.502.00ZonePoints per shotScored, Restricted area: 1.43Expected, Restricted area: 1.30Restricted areaScored, Paint: 1.10Expected, Paint: 0.88PaintScored, Midrange: 1.07Expected, Midrange: 0.87MidrangeScored, Corner three: 0.94Expected, Corner three: 1.15Corner threeScored, Above-break three: 1.17Expected, Above-break three: 1.07Above-break three

1,322 field goal attempts. Expected points are our model's value of the shots he took in each zone.

What the chart shows:

  • He scored more than expected in four of five zones. The biggest gaps are in the paint (1.103 against 0.884, 76 points over 348 shots) and midrange (1.072 against 0.867, 68 points over 332).
  • The corner three is the exception: 5 of 16 (31.3%), 3.4 points below expectation. With 16 attempts that is too few shots to read.
  • Summed over all five zones, he scored 215 points more than the model expected from his shot locations. A model value is an estimate, so treat the size of the gap as approximate.

4. Draw the court

Court coordinates are in feet: x runs 0 to 50 across the court and y is the distance from the basket, which is at (25, 0). Each shot row has x, y, made and pts (2 or 3). The script draws the lines in those same units, so the three-point arc and the paint land where the shots do, and colors each shot by result. Locations are whole feet, so shots from the same spot stack.

import json
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.patches import Arc, Circle, Rectangle

shots = pd.DataFrame(json.load(open("sga_shot_chart_2026.json"))["shots"])
print(len(shots), "shots,", int(shots["made"].sum()), "made")
print(shots.groupby("pts")["made"].agg(["size", "mean"]).round(3).to_string())

fig, ax = plt.subplots(figsize=(7, 6.6))
# Court lines, in feet. The basket is at (25, 0) and y runs away from it.
ax.add_patch(Circle((25, 0), 0.75, fill=False))                      # rim
ax.plot([22, 28], [-1.25, -1.25], color="black")                       # backboard
ax.add_patch(Rectangle((17, -5.25), 16, 19, fill=False))               # paint, free throw line at y = 13.75
ax.add_patch(Arc((25, 13.75), 12, 12, theta1=0, theta2=180))           # free throw circle
ax.add_patch(Arc((25, 0), 8, 8, theta1=0, theta2=180))                 # restricted area
ax.add_patch(Arc((25, 0), 47.5, 47.5, theta1=22, theta2=158))          # three-point arc
ax.plot([3, 3], [-5.25, 8.9], color="black")                           # corner threes
ax.plot([47, 47], [-5.25, 8.9], color="black")
ax.add_patch(Rectangle((0, -5.25), 50, 47, fill=False))               # baseline and sidelines

missed, made = shots[~shots["made"]], shots[shots["made"]]
ax.scatter(missed["x"], missed["y"], s=10, c="#c0392b", alpha=0.45, label="Missed")
ax.scatter(made["x"], made["y"], s=10, c="#1f7a4d", alpha=0.45, label="Made")
ax.set_xlim(-1, 51)
ax.set_ylim(-6, 42)
ax.set_aspect("equal")
ax.axis("off")
ax.legend(loc="upper right")
plt.savefig("sga_shot_chart.png", dpi=150, bbox_inches="tight")

Output

1322 shots, 731 made
     size   mean
pts             
2    1024  0.602
3     298  0.386

The image is saved as sga_shot_chart.png. He made 731 of 1,322 field goal attempts (55.3%): 60.2% on 1,024 twos and 38.6% on 298 threes. Pass team="OKC" instead of player_id for a team's chart, add opponent=True for the shots its opponents took, or pass a game_id for one game.

5. Compare players on shot quality and shot making

Expected points per shot is a measure of the shots a player takes. Points per shot is what he made of them. The gap between the two is shot making. Without include_shots the call returns the zone table only, so these two players cost 10 credits each plus 1 for the search.

import json
import pandas as pd
from dunkapi import Client

client = Client()


def profile(name, chart):
    z = pd.DataFrame(chart["zones"])
    z = z[z["zone"] != "free_throw"]
    fga = z["attempts"].sum()
    return {
        "player": name,
        "fga": fga,
        "three_share": z[z["zone"].str.contains("3")]["attempts"].sum() / fga,
        "points_per_shot": (z["points_per_shot"] * z["attempts"]).sum() / fga,
        "expected_per_shot": (z["expected_points_per_shot"] * z["attempts"]).sum() / fga,
    }


rows = [profile("Shai Gilgeous-Alexander", json.load(open("sga_shot_chart_2026.json")))]
for query in ["Stephen Curry", "Nikola Jokic"]:
    player = client.search_players(query, limit=1)["players"][0]
    chart = client.get_shot_chart(player_id=player["player_id"], season=2026)
    rows.append(profile(player["name"], chart))

compare = pd.DataFrame(rows)
compare["made_vs_expected"] = compare["points_per_shot"] - compare["expected_per_shot"]
print(compare.round(3).to_string(index=False))
print("credits left:", client.last_credits_remaining)

Output

                 player  fga  three_share  points_per_shot  expected_per_shot  made_vs_expected
Shai Gilgeous-Alexander 1322        0.225            1.193              1.030             0.163
          Stephen Curry  799        0.606            1.174              0.995             0.178
           Nikola Jokic 1134        0.262            1.237              1.019             0.218
credits left: 3525

How to read it:

  • Shot mix. 60.6% of Curry's attempts were threes, against 22.5% for Gilgeous-Alexander and 26.2% for Jokic.
  • Shot quality. The three have close expected values per shot, 0.995 to 1.030.
  • Shot making. All three scored well above those values, by 0.163, 0.178 and 0.218 points per shot. One season of shots has noise in it, so a gap of a few hundredths between players is not a ranking.

Tools and credits

One full run: 33 credits.

What you can do with the data

You may store these rows, train models and analyze them, and build products that show your users what you derive. You may not redistribute the rows as a dataset or API of its own. Expected points are our model's estimate, not a record of what happened.

Details: data timing and rights.

What to do next

Start with 500 free credits every month

No card. pip install dunkapi, REST or MCP.