Build with StatpadTypeScript SDKPremier League
A shot map of Manchester United 4–4 Aston Villa in 125 lines of TypeScript
Every shot in Statpad's Premier League play-by-play has pitch coordinates. This script turns one 8-goal draw into an SVG shot map and a score timeline, and covers the two coordinate traps.
Plot the shots from Manchester United 4–4 Aston Villa straight out of Statpad's play-by-play and you get this map. It has 38 shots, and every one of them is at the same end of the pitch. Villa's 12, in black, land in front of the goal United attacked.
The data is right. The SoccerPlay schema says how it works in one sentence: "Positions run 0-100 from the acting team's view: x from its own goal line to the one it attacks, y across the pitch." Every team attacks x = 100. To put both teams on one pitch you turn one of them around, and the y axis has to turn with it. This post builds that map and a score timeline from three API requests and one TypeScript file.
The match
Aston Villa played at Old Trafford on 8 November 2026. Everything in this post comes from the recorded API responses for the match, which statpad.dev publishes, so you can check each number without a key:
- game.json, the body of
GET /v1/epl/games/{id} - plays.json, from
/plays - roster.json, from
/roster
Villa scored in the 1st and 4th minutes. A Bruno Fernandes penalty and a Youri Tielemans goal made it 2–2 before half-time. John McGinn's penalty in the 48th minute and Leon Goretzka's goal in the 53rd put Villa 4–2 up. United took 26 shots to Villa's 12, and they still needed Joshua Zirkzee at 90+2 and a Patrick Dorgu header at 90+6 to draw. They never led.
Three requests
The script reads the game for team names and the final score, then every play, then the game roster for player names. paginate follows next_cursor until it's null. This match fits in one page of each: 106 plays against a default page size of 500, and 40 roster entries against a default of 100. So the script makes three requests.
import { writeFile } from 'node:fs/promises';
import { paginate, Statpad, type Play } from '@statpad/sdk';
const args = process.argv.slice(2);
const fromSamples = args.includes('--from-samples');
const naive = args.includes('--naive');
const gameId = args.find((arg) => !arg.startsWith('--')) ?? '01a1eee7-199e-7db2-99d7-b07cfeb058aa';
// --from-samples answers the script's three requests with the recorded responses on statpad.dev.
const samples: typeof fetch = async (input) => {
const { pathname } = new URL(input instanceof Request ? input.url : String(input));
const file = pathname.endsWith('/plays') ? 'plays' : pathname.endsWith('/roster') ? 'roster' : 'game';
return fetch(`https://statpad.dev/samples/epl-man-utd-aston-villa/${file}.json`);
};
const statpad = new Statpad({ apiKey: process.env.STATPAD_API_KEY ?? '', ...(fromSamples && { fetch: samples }) });
const path = { league: 'epl', game_id: gameId };
const { data: game } = await statpad.games.getGame({ path });
const plays: Play[] = [];
for await (const page of paginate(statpad.playByPlay.listPlays, { path })) plays.push(...page.data);
const names = new Map<string, string>();
const rosterTeam = new Map<string, string>();
for await (const page of paginate(statpad.games.listGameRoster, { path })) {
for (const player of page.players) names.set(player.id, player.last_name || player.full_name);
for (const entry of page.data) rosterTeam.set(entry.player_id, entry.team_id);
}
plays.sort((a, b) => a.sequence - b.sequence || a.id.localeCompare(b.id));The --from-samples flag replaces the SDK's fetch with a function that answers each request with the matching recorded file. The SDK calls and everything after them are the same in both modes. If you leave the flag off, the script calls api.statpad.dev with your STATPAD_API_KEY. With no key set, it stops at the first request:
StatpadError: 401 unauthorized: Send an API key as "Authorization: Bearer <key>".Here is the 90+6 equalizer from plays.json, trimmed to the fields this post uses and reordered:
{
"id": "01a1d60f-c5d1-7e0b-88cd-ac3672b29601",
"sequence": 1794162415000,
"period": 2,
"clock_seconds": null,
"type": "goal",
"team_id": "01a1d60f-c5d1-7d79-9edc-b4994b109b29",
"home_score": 4,
"away_score": 4,
"participants": [
{ "player_id": "01a1d60f-c5d1-7d81-a064-5b6366ba95ea", "role": "assist", "team_id": "01a1d60f-c5d1-7d79-9edc-b4994b109b29" },
{ "player_id": "01a1d60f-c5d1-7d88-ab3b-6208509e4b56", "role": "scorer", "team_id": "01a1d60f-c5d1-7d79-9edc-b4994b109b29" }
],
"soccer": {
"play_type": "goal",
"minute": 90,
"added_minute": 6,
"body_part": "head",
"field_x": 97.3,
"field_y": 48.1,
"end_x": 100,
"end_y": 48.3
}
}field_x 97.3 puts the header 2.7 units from the goal line United attacked, and end_x 100 says the ball reached that line. All eight goals in the match have end_x 100.
Picking the shots
Six shot types appear in this match. The script also lists penalty_saved and penalty_missed, which this match doesn't have, so it works on other games too.
const SHOT_TYPES = ['goal', 'penalty_goal', 'penalty_saved', 'penalty_missed', 'shot_on_target', 'shot_off_target', 'shot_blocked', 'shot_woodwork'];
const shots = plays.filter((p) => SHOT_TYPES.includes(p.type) && p.soccer?.field_x != null && p.soccer.field_y != null);
const isGoal = (p: Play) => p.type === 'goal' || p.type === 'penalty_goal';
const shooter = (p: Play) => p.participants.find((x) => x.role === 'scorer' || x.role === 'shooter')?.player_id ?? '';
for (const shot of shots) {
if (rosterTeam.get(shooter(shot)) !== shot.team_id) throw new Error(`play ${shot.id}: shooter isn't on the shooting team's roster`);
}All 38 shots have field_x and field_y. By type:
| Type | Manchester United | Aston Villa |
|---|---|---|
goal |
3 | 3 |
penalty_goal |
1 | 1 |
shot_on_target |
5 | 2 |
shot_off_target |
9 | 4 |
shot_blocked |
7 | 2 |
shot_woodwork |
1 | 0 |
| Total | 26 | 12 |
A shot_on_target play is a shot that was saved. Goals have their own types, so if you want the usual "shots on target" figure, add the goals: 9 for United and 6 for Villa.
The player who shot is the participant with the role scorer on a goal and shooter on any other shot. Assists are a separate participant. The play's description names the scorer too, as in "Goal: Patrick Dorgu (Manchester United), header, assisted by Bruno Fernandes. Manchester United 4, Aston Villa 4.", but the script takes names from the roster. It also checks each shooter's team in the roster against the play's team_id and throws if they differ. All 38 pass. Run a check like this before you put a name on a graphic people will share.
Trap one: both teams attack x = 100
The first map plotted field_x as it came, so both teams attack the right-hand goal. The fix belongs in the one function that turns a play into a point on the pitch:
// Pitch: 105 x 68 m at 10 px per metre. Every position is 0-100 from the shooting team's own goal,
// so the away team is turned 180 degrees (both axes) to attack the left goal.
const W = 1050, H = 680;
function toPitch(p: Play) {
const [x, y] = [p.soccer!.field_x!, p.soccer!.field_y!];
const [fx, fy] = !naive && p.team_id !== home ? [100 - x, 100 - y] : [x, y];
return { x: (fx / 100) * W, y: (1 - fy / 100) * H };
}United, the home team, keep their coordinates and attack to the right. Villa get 100 - x and attack to the left. The --naive flag skips the turn, which is how the first map was made.
Trap two: y is measured from the shooter's side too
If you flip x for one team and stop there, Villa's shots end up on the wrong wing. The y axis is also measured from the acting team's side. Six shots in this match came from the right side of the box, three by each team, and their field_y runs from 27.3 to 36.6. Boubacar Kamara's blocked shot for Villa, from a tight angle on the right, is at 31. The two shots from the left were both United's: Matheus Cunha's from the left side of the box at 70.6, and Bruno Fernandes's from long range on the left at 81.2. For both teams, low y is the right-hand side.
On a real pitch, the two teams' right-hand sides are opposite touchlines. So the away team needs both axes flipped, which is a turn of 180 degrees, and toPitch uses [100 - x, 100 - y]. A team attacking to the right has its right-hand side at the bottom of the screen, so screen y is 1 - fy / 100 of the height. Here are the same 38 shots with Villa turned around. Filled circles are goals.
Alysson's opening goal, from the right side of the box, now sits in the upper half of the left-hand penalty area. That is the right-hand side for a player attacking the left goal.
How big is the pitch?
The data doesn't say. The script draws a 105 by 68 metre pitch, at 10 SVG units per metre, and stretches the 0 to 100 grid over it in both directions.
The two penalties make a useful check. Both are at exactly (88.5, 50). The 50 is the centre of the pitch, as it should be. On a 105-metre pitch, though, x 88.5 is 12.1 metres from the goal line, and the penalty spot is 11 metres out. Treat the grid as good for plotting only, because shot distances in metres computed from it come out wrong. On the map, the difference is smaller than the dots.
A timeline built from match minutes
Soccer plays have clock_seconds null. The schema explains why: "Soccer clocks count up and stoppage time is only a minute count, so a soccer clock_seconds is null and the match minute is in the soccer block." The script measures time as minute + added_minute and keeps the plays in the order listPlays returns them, by (sequence, id).
That order matters at the end of this match. Two goals are both minute 90, and three plays share 90+6: Mason Mount's header wide, a corner, and Dorgu's headed goal. Sort by minute and those three come out in whatever order your sort leaves them.
// Score timeline. Soccer plays have no clock_seconds, so time comes from minute + added_minute.
const clock = (p: Play) => (p.soccer?.minute ?? 0) + (p.soccer?.added_minute ?? 0);
const half1 = Math.max(...plays.filter((p) => p.period === 1).map(clock));
const t = (p: Play) => (p.period === 1 ? clock(p) : half1 + clock(p) - 45);
const total = Math.max(...plays.map(t));
const X = (m: number) => 180 + (m / total) * 1100 + (m > half1 ? 30 : 0);
const score = (p?: Play) => (p?.home_score ?? 0) + (p?.away_score ?? 0);
const scoring = plays.filter((p, i) => score(p) > score(plays[i - 1]));
const states = [{ t: 0, h: 0, a: 0 }, ...scoring.map((p) => ({ t: t(p), h: p.home_score ?? 0, a: p.away_score ?? 0 })), { t: total, h: 0, a: 0 }];The first half's period_end play is at 45+5 and the second half's is at 90+9, so the timeline is 104 minutes long with a gap at half-time. The script finds goals by reading each play's home_score and away_score and marking the plays where their sum goes up. It never counts goal events itself. The bar under the goals is black while Villa lead, blue while United lead and grey while the score is level.
The bar is grey for three short spells: the first minute, the 44th to the 48th, and the last three minutes after Dorgu's goal. Villa led for the rest of the match, and the bar never turns blue.
What Statpad doesn't serve
A soccer graphic often shows four things the API leaves out. Here is each one and its workaround:
- Expected goals. There is no xG field on plays or in the box score, so this map has no xG sizing.
- Team shot totals. The box score schema has a
teamsarray, but it is empty for this match, and only the player lines carry stats. Count shots from plays, as above, or add up the player lines. Theirtotal_shotssum to 26 and 12, and theirshots_on_targetto 9 and 6, which agrees with the plays. - Score by half.
period_scoresis empty in both the game and the box score. Readhome_scoreandaway_scorefrom the last play of each period instead. - Pitch dimensions. As above, pick one and say which.
Run it
The script uses Node's built-in TypeScript type stripping, so it needs Node 22.18 or later. The SDK on its own needs Node 20. In an empty folder with shotmap.ts:
npm init -y
npm pkg set type=module
npm install @statpad/sdk@~0.1.0
node shotmap.ts --from-samplesIt writes shotmap.svg and timeline.svg to the current folder and prints:
106 plays, 38 shots (Manchester United 26, Aston Villa 12), 8 goals
1' Alysson 0–1
4' Jackson 0–2
16' Fernandes, pen 1–2
44' Tielemans 2–2
48' McGinn, pen 2–3
53' Goretzka 2–4
90+2' Zirkzee 3–4
90+6' Dorgu, header 4–4Add --naive to write shotmap-naive.svg, the one-ended map. To draw a match from the API, drop the flag, set STATPAD_API_KEY and pass the game's id: node shotmap.ts <game_id>. The key's plan has to include epl, or the first request fails with forbidden.
The three images in this post are the script's SVG output, unedited.
The whole script
import { writeFile } from 'node:fs/promises';
import { paginate, Statpad, type Play } from '@statpad/sdk';
const args = process.argv.slice(2);
const fromSamples = args.includes('--from-samples');
const naive = args.includes('--naive');
const gameId = args.find((arg) => !arg.startsWith('--')) ?? '01a1eee7-199e-7db2-99d7-b07cfeb058aa';
// --from-samples answers the script's three requests with the recorded responses on statpad.dev.
const samples: typeof fetch = async (input) => {
const { pathname } = new URL(input instanceof Request ? input.url : String(input));
const file = pathname.endsWith('/plays') ? 'plays' : pathname.endsWith('/roster') ? 'roster' : 'game';
return fetch(`https://statpad.dev/samples/epl-man-utd-aston-villa/${file}.json`);
};
const statpad = new Statpad({ apiKey: process.env.STATPAD_API_KEY ?? '', ...(fromSamples && { fetch: samples }) });
const path = { league: 'epl', game_id: gameId };
const { data: game } = await statpad.games.getGame({ path });
const plays: Play[] = [];
for await (const page of paginate(statpad.playByPlay.listPlays, { path })) plays.push(...page.data);
const names = new Map<string, string>();
const rosterTeam = new Map<string, string>();
for await (const page of paginate(statpad.games.listGameRoster, { path })) {
for (const player of page.players) names.set(player.id, player.last_name || player.full_name);
for (const entry of page.data) rosterTeam.set(entry.player_id, entry.team_id);
}
plays.sort((a, b) => a.sequence - b.sequence || a.id.localeCompare(b.id));
const SHOT_TYPES = ['goal', 'penalty_goal', 'penalty_saved', 'penalty_missed', 'shot_on_target', 'shot_off_target', 'shot_blocked', 'shot_woodwork'];
const shots = plays.filter((p) => SHOT_TYPES.includes(p.type) && p.soccer?.field_x != null && p.soccer.field_y != null);
const isGoal = (p: Play) => p.type === 'goal' || p.type === 'penalty_goal';
const shooter = (p: Play) => p.participants.find((x) => x.role === 'scorer' || x.role === 'shooter')?.player_id ?? '';
for (const shot of shots) {
if (rosterTeam.get(shooter(shot)) !== shot.team_id) throw new Error(`play ${shot.id}: shooter isn't on the shooting team's roster`);
}
const home = game.game.home_team_id;
const color = (p: Play) => (p.team_id === home ? '#2f5bea' : '#0b0b0b');
const minute = (p: Play) => `${p.soccer?.minute ?? 0}${p.soccer?.added_minute ? `+${p.soccer.added_minute}` : ''}'`;
const label = (p: Play) => `${names.get(shooter(p)) ?? '?'}${p.type === 'penalty_goal' ? ', pen' : p.soccer?.body_part === 'head' ? ', header' : ''}`;
const esc = (s: string) => s.replace(/&/g, '&').replace(/</g, '<');
const svg = (box: string, body: string) => {
const [x, y, width, height] = box.split(' ');
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${box}" font-family="Instrument Sans" fill="#0b0b0b">` +
`<rect x="${x}" y="${y}" width="${width}" height="${height}" fill="#ffffff"/>${body}</svg>\n`;
};
const mono = (s: string, extra = '') => `<tspan font-family="Geist Mono"${extra}>${esc(s)}</tspan>`;
// Pitch: 105 x 68 m at 10 px per metre. Every position is 0-100 from the shooting team's own goal,
// so the away team is turned 180 degrees (both axes) to attack the left goal.
const W = 1050, H = 680;
function toPitch(p: Play) {
const [x, y] = [p.soccer!.field_x!, p.soccer!.field_y!];
const [fx, fy] = !naive && p.team_id !== home ? [100 - x, 100 - y] : [x, y];
return { x: (fx / 100) * W, y: (1 - fy / 100) * H };
}
const end = (gx: number, d: number) =>
`<rect x="${Math.min(gx, gx + d * 165)}" y="138.4" width="165" height="403.2"/>` +
`<rect x="${Math.min(gx, gx + d * 55)}" y="248.4" width="55" height="183.2"/>` +
`<rect x="${Math.min(gx, gx - d * 20)}" y="303.4" width="20" height="73.2"/>` +
`<circle cx="${gx + d * 110}" cy="340" r="3" fill="#99999b"/>` +
`<path d="M${gx + d * 165} 266.9A91.5 91.5 0 0 ${d > 0 ? 1 : 0} ${gx + d * 165} 413.1"/>`;
const pitch = `<g fill="none" stroke="#ececee" stroke-width="3"><rect width="${W}" height="${H}"/>` +
`<path d="M525 0V${H}"/><circle cx="525" cy="340" r="91.5"/><circle cx="525" cy="340" r="3" fill="#99999b"/>${end(0, 1)}${end(W, -1)}</g>`;
const dots = shots.map((p) => {
const { x, y } = toPitch(p);
return `<circle cx="${x.toFixed(1)}" cy="${y.toFixed(1)}" r="${isGoal(p) ? 13 : 9}" fill="${isGoal(p) ? color(p) : '#ffffff'}" stroke="${color(p)}" stroke-width="2.5"/>`;
});
const labels = [home, game.game.away_team_id].flatMap((team) => {
const right = naive || team === home;
const goals = shots.filter((p) => isGoal(p) && p.team_id === team).sort((a, b) => toPitch(a).y - toPitch(b).y);
return goals.map((p, i) => {
const { x, y } = toPitch(p);
const [lx, ly] = [right ? W + 40 : -40, 340 + (i - (goals.length - 1) / 2) * 40 + (naive && team !== home ? 170 : 0)];
return `<path d="M${x.toFixed(1)} ${y.toFixed(1)}L${lx} ${ly}" stroke="${color(p)}" stroke-width="1.5" fill="none"/>` +
`<text x="${lx + (right ? 8 : -8)}" y="${ly + 7}" font-size="20" text-anchor="${right ? 'start' : 'end'}">${mono(minute(p), ' fill="#606062"')} ${esc(label(p))}</text>`;
});
});
const count = (team: string) => shots.filter((p) => p.team_id === team).length;
const [homeName, awayName] = [game.home_team.market, game.away_team.market];
const legend = (y: number, fill: string, text: string) =>
`<circle cx="10" cy="${y}" r="9" fill="${fill}"/><text x="30" y="${y + 7}" font-size="20">${esc(text)}</text>`;
const shotmap = svg('-280 -150 1610 960',
`<text y="-90" font-size="36" font-weight="600">${esc(homeName)} ${mono(`${game.game.home_score}–${game.game.away_score}`)} ${esc(awayName)}</text>` +
`<text y="-45" font-size="22" fill="#606062">${shots.length} shots: ${esc(homeName)} ${count(home)}, ${esc(awayName)} ${count(game.game.away_team_id)}. Filled circles are goals.${naive ? ' Positions as served, not rotated.' : ''}</text>` +
pitch + dots.join('') + labels.join('') +
legend(735, '#2f5bea', `${homeName}, attacking right`) + legend(775, '#0b0b0b', `${awayName}, ${naive ? 'also attacking right' : 'attacking left'}`));
await writeFile(naive ? 'shotmap-naive.svg' : 'shotmap.svg', shotmap);
// Score timeline. Soccer plays have no clock_seconds, so time comes from minute + added_minute.
const clock = (p: Play) => (p.soccer?.minute ?? 0) + (p.soccer?.added_minute ?? 0);
const half1 = Math.max(...plays.filter((p) => p.period === 1).map(clock));
const t = (p: Play) => (p.period === 1 ? clock(p) : half1 + clock(p) - 45);
const total = Math.max(...plays.map(t));
const X = (m: number) => 180 + (m / total) * 1100 + (m > half1 ? 30 : 0);
const score = (p?: Play) => (p?.home_score ?? 0) + (p?.away_score ?? 0);
const scoring = plays.filter((p, i) => score(p) > score(plays[i - 1]));
const states = [{ t: 0, h: 0, a: 0 }, ...scoring.map((p) => ({ t: t(p), h: p.home_score ?? 0, a: p.away_score ?? 0 })), { t: total, h: 0, a: 0 }];
const bar = (a: number, b: number, stroke: string) => [[a, Math.min(b, half1)], [Math.max(a, half1 + 1e-9), b]]
.filter(([from, to]) => to > from).map(([from, to]) => `<path d="M${X(from)} 300H${X(to)}" stroke="${stroke}" stroke-width="10"/>`).join('');
const lead = states.slice(0, -1).map((s, i) => bar(s.t, states[i + 1].t, s.h > s.a ? '#2f5bea' : s.a > s.h ? '#0b0b0b' : '#99999b'));
// Labels are placed right to left, so a leader line never crosses a label in a lower row.
const rows: Record<string, number[]> = {};
const marks = scoring.toReversed().map((p) => {
const up = p.team_id !== home, x = X(t(p));
const right = x + `${minute(p)} ${label(p)} ${p.home_score}–${p.away_score}`.length * 11;
const lane = (rows[String(up)] ??= []);
let row = lane.findIndex((left) => right < left - 20);
if (row < 0) row = lane.push(0) - 1;
lane[row] = x;
const ly = up ? 240 - row * 40 : 370 + row * 40;
return `<path d="M${x} 300V${ly + (up ? 8 : -22)}" stroke="${color(p)}" stroke-width="1.5"/><circle cx="${x}" cy="300" r="11" fill="${color(p)}" stroke="#ffffff" stroke-width="3"/>` +
`<text x="${x}" y="${ly}" font-size="20" fill="${color(p)}">${mono(minute(p))} ${esc(label(p))} ${mono(`${p.home_score}–${p.away_score}`, ' font-weight="600"')}</text>`;
});
const ticks = [0, 15, 30, 45, half1 + 15, half1 + 30, half1 + 45, total].map((m) =>
`<text x="${X(m)}" y="500" font-size="18" fill="#606062" text-anchor="middle">${mono(m <= half1 ? `${m}'` : m === total ? `90+${total - half1 - 45}'` : `${m - half1 + 45}'`)}</text>`);
const timeline = svg('0 0 1600 540',
`<text x="40" y="60" font-size="32" font-weight="600">Score by minute</text>` +
`<text x="40" y="100" font-size="20" fill="#606062">The bar is black while ${esc(awayName)} lead, blue while ${esc(homeName)} lead, grey when level.</text>` +
`<text x="40" y="250" font-size="20" fill="#606062">${esc(awayName)}</text><text x="40" y="380" font-size="20" fill="#2f5bea">${esc(homeName)}</text>` +
lead.join('') +
`<text x="${X(half1) + 15}" y="330" font-size="16" fill="#606062" text-anchor="middle">${mono('HT')}</text>` + marks.join('') + ticks.join(''));
await writeFile('timeline.svg', timeline);
console.log(`${plays.length} plays, ${shots.length} shots (${homeName} ${count(home)}, ${awayName} ${count(game.game.away_team_id)}), ${scoring.length} goals`);
for (const p of scoring) console.log(` ${minute(p).padEnd(6)} ${label(p).padEnd(20)} ${p.home_score}–${p.away_score}`);More from Build with Statpad
- Test that your live client gets a real game rightA six-test node:test file sends all 1,277 changes of a recorded NFL game through your change handler and checks what your app would show at the moments that break live clients.
- Ask Claude about an NFL game while it replays on your laptopA small Node server replays the recorded Bills at Vikings game on localhost. Point @statpad/mcp at it, ask Claude who has the ball, then move the game forward and watch the answer change when replay overturns a fumble.
- A live NFL scoreboard in SwiftUI, and the small server that holds the keyA Node server on @statpad/sdk holds the Statpad key and one stream subscription, and a SwiftUI app resumes from it by seq, tested against a recorded Bills at Vikings game.
- A fantasy football scoreboard for your Discord channelA first project with the Statpad API. One small Node script scores a fantasy matchup from NFL box scores and keeps a single Discord message up to date through a channel webhook.