- What is a heatmap and passing map in sports analytics
- What sports data APIs to use for football visualization
- How to get match data through API to build player heatmaps
- How to create a heatmap of shots and player actions using API data
- How to build a passing map of team passes based on event API
- Tools and libraries for visualizing sports data from APIs (Python, JavaScript)
What is a heatmap and passing map in sports analytics
A heatmap in sports analytics is a heat map that shows the concentration of actions on the court or field. The color scale reflects the density of events: the hotter the area, the more often shots, tackles, passes, or ball touches occurred there. On a football field, this helps to literally see the team’s style: high pressure, play through the flanks, loading the penalty area, or control in the center.
A passing map is a pass map that displays the direction and frequency of passes between players. Typically, the diagram shows the positions of the footballers, lines between them, and the thickness of the lines related to the number of passes. Such visualization allows assessing through whom the attack is built, how the first pass works, how actively full-backs are used, and whether there is a bias towards one of the zones.
Both visualizations are critical for scouting, tactical analysis, match preparation, and betting. They help make decisions based on actual data rather than subjective impressions. To systematically build heatmaps and passing maps without manual input, a reliable source of event statistics is necessary — a sports data API. This is the kind of programmatic access to matches, teams, players, and statistics that the platform provides. Sports data API api-sport.ru, supporting football, basketball, hockey, tennis, table tennis, esports, and other sports.
What sports data APIs to use for football visualization
To build visual heatmaps and passing maps for football, three groups of data are important: match information, detailed statistics, and events during the game. Within the Sport Events API on the domain api.api-sport.ru, this is implemented through the v2 family of endpoints. They allow you to obtain a list of matches, detailed information about a specific match, team lineups, advanced statistics, and even bookmaker odds through the oddsBase block.
Basic requests are made to endpoints of the type v2 football matches and v2 football matches {matchId}. In the response, you receive a Match object with fields tournament, teams, score, venue, and most importantly — an array matchStatistics with breakdowns by periods and groups of metrics. It contains key metrics for visualization: ball possession, total shots, shots on target, touches in the penalty area, passes into the final third, accurate passes, and much more. This data can be aggregated by areas of the field and used as a basis for heatmaps and passing maps.
A separate endpoint v2 football matches {matchId} events returns the chronology of liveEvents: goals, cards, substitutions, and other important events. Based on them, timelines and combined graphs are formed. In advanced projects, the event stream can be conveniently obtained in real-time via WebSocket. WebSocket support is already in the service development plans. api-sport.ru, which will pave the way for online heatmaps and live passing maps right during the match. Additionally, the bookmaker API with odds allows overlaying market dynamics on top of the visualization.
How to get match data through API to build player heatmaps
The first step to any heatmap is obtaining accurate match data. In the Sport Events API, this is done using the endpoint v2 football matches {matchId}. In the response, you receive a single Match object, which already contains teams, lineups with each player’s position in the lineup object, the current score, match status, and an array matchStatistics with detailed statistics by periods ALL, 1ST, 2ND.
To send requests to the API, an authorization key is required. It can be generated in the secure section of the platform at your personal account at api-sport.ru. After that, it is enough to pass the key in the Authorization header. Below is an example of obtaining detailed information about a football match by ID in a browser or Node.js using fetch.
const API_KEY = 'ВАШ_API_КЛЮЧ';
const matchId = 14570728;
fetch('https://api.api-sport.ru/v2/football/matches/' + matchId, {
headers: {
Authorization: API_KEY
}
})
.then(r => r.json())
.then(match => {
// Общая информация о матче
console.log(match.homeTeam.name, 'vs', match.awayTeam.name);
// Пример доступа к статистике по всем периодам
const allPeriod = match.matchStatistics.find(s => s.period === 'ALL');
const shotsGroup = allPeriod.groups.find(g => g.groupName === 'Shots');
console.log('Всего ударов хозяев:', shotsGroup.statisticsItems.find(i => i.key === 'totalShotsOnGoal').homeValue);
});
At the next stage, data from matchStatistics can be transformed into an activity matrix by zones. For a simple heatmap, aggregated metrics are used. For example, touches in the penalty area touchesInOppBox, passes into the final third finalThirdEntries, and shots from different zones. If your plan additionally includes an event stream with action coordinates, you can already build full-fledged heatmaps by x and y, dividing the field into a grid and counting the number of events in each cell.
How to create a heatmap of shots and player actions using API data
When creating a shot heatmap, it is important to correctly extract metrics related to attacking actions from the API. In the matchStatistics object, there are groups Shots and Attack, which contain metrics totalShotsOnGoal, shotsOnGoal, totalShotsInsideBox, totalShotsOutsideBox, touchesInOppBox, bigChanceCreated, and others. These values already provide an idea of the zones and frequency with which the team or a specific player creates a threat.
To turn statistics into a heatmap, the field is usually divided into a grid, with each cell corresponding to a sector. If you have the coordinates of shots and actions, you simply count the number of events per cell. When working only with aggregated data from matchStatistics, you can model intensity across vertical and horizontal bands, for example, separately assessing the left flank, right flank, and central zone, as well as dividing the field into thirds.
Below is an example in Python that retrieves match data via the API, extracts key metrics on shots, and prepares the foundation for visualizing a heatmap as a two-dimensional matrix. For a real project, you can replace the conditional matrix with the result of processing coordinates.
import requests
API_KEY = 'ВАШ_API_КЛЮЧ'
MATCH_ID = 14570728
url = f'https://api.api-sport.ru/v2/football/matches/{MATCH_ID}'
resp = requests.get(url, headers={'Authorization': API_KEY})
match = resp.json()
all_period = next(s for s in match['matchStatistics'] if s['period'] == 'ALL')
shots_group = next(g for g in all_period['groups'] if g['groupName'] == 'Shots')
shots_total = next(i for i in shots_group['statisticsItems'] if i['key'] == 'totalShotsOnGoal')
inside_box = next(i for i in shots_group['statisticsItems'] if i['key'] == 'totalShotsInsideBox')
outside_box = next(i for i in shots_group['statisticsItems'] if i['key'] == 'totalShotsOutsideBox')
print('Удары всего:', shots_total['homeValue'], shots_total['awayValue'])
print('Из штрафной:', inside_box['homeValue'], inside_box['awayValue'])
print('Из-за пределов:', outside_box['homeValue'], outside_box['awayValue'])
# Заготовка под тепловую матрицу 3х3 по зонам поля
heatmap_matrix = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
]
The resulting matrix can be conveniently drawn using visualization libraries, coloring the cells based on intensity. If you additionally connect your own tracking data or shot coordinates to the Sport Events API, they can be combined in one pipeline to build a detailed heatmap of each player’s actions down to a specific point on the field.
How to build a passing map of team passes based on event API
The passing map helps to see the structure of ball play through connections between players. Conditionally, each player is a node of the graph, and the passes between them are edges, the thickness and color of which depend on the frequency and accuracy of the passes. To calculate such connections, two layers of data are needed: the team composition with player identifiers and events reflecting passes between them. The first layer provides the endpoint v2 football matches {matchId} through the homeTeam, awayTeam, and lineup objects. The second layer is formed based on the event feed and statistics from matchStatistics.
The endpoint v2 football matches {matchId} events returns an array of events with LiveEvent during the match. It is especially useful in combination with aggregated metrics from the Passes group, which includes accuratePasses, passes, finalThirdEntries, accurateLongBalls, accurateCross. This data allows you to assess the overall volume and quality of passes for the team, and then distribute them across player connections if your plan includes an extended event stream specifying the passer and receiver of the pass.
Below is an example in JavaScript that retrieves the list of match events and prepares the structure for a simple passing graph. The passes array assumes events where passerId and receiverId have already been highlighted. Such a structure can be obtained either from an advanced tariff plan or from your own preprocessing of raw data.
const API_KEY = 'ВАШ_API_КЛЮЧ';
const matchId = 14570728;
async function loadEvents() {
const res = await fetch('https://api.api-sport.ru/v2/football/matches/' + matchId + '/events', {
headers: { Authorization: API_KEY }
});
const data = await res.json();
return data.events;
}
function buildPassingGraph(passes) {
const links = {};
passes.forEach(p => {
const key = p.passerId + '-' + p.receiverId;
if (!links[key]) {
links[key] = { from: p.passerId, to: p.receiverId, count: 0 };
}
links[key].count += 1;
});
return Object.values(links);
}
The resulting array of connections can be passed to any graph visualization library and drawn as a passing map over the field scheme. In the future, the platform api-sport.ru plans to develop real-time tools based on WebSocket and AI modules. This will open up the possibility of building passing maps with online updates and automatic insights, such as identifying key connections and unconventional play patterns.
Tools and libraries for visualizing sports data from APIs (Python, JavaScript)
After you have set up data retrieval via the Sport Events API, the next step is to choose a visualization stack. In the Python ecosystem, popular combinations are pandas plus matplotlib or seaborn for static graphs and plotly for interactive dashboards. For football fields, the specialized library mplsoccer is often used, which simplifies the drawing of markings, heatmaps, and passing maps on a standard football field.
In the browser, the main tool for complex interactive graphics remains D3.js. For faster implementations, Chart.js, ECharts, or Highcharts are suitable, which handle heat matrices and grid charts well. Client applications can be conveniently connected to the API via fetch or axios, and in real-time, data can be updated via WebSocket, which is planned to be added to the infrastructure of api-sport.ru. This will allow building live panels with an online heatmap and updating passing maps without reloading the page.
Below is an example of minimal code in Python that retrieves match data from an API and builds a simple heatmap based on a conditional set of shot coordinates using matplotlib. In practice, instead of the list of shots, you will use real coordinates obtained from your own tracking or an enhanced event feed.
import requests
import numpy as np
import matplotlib.pyplot as plt
API_KEY = 'ВАШ_API_КЛЮЧ'
MATCH_ID = 14570728
# Получаем матч (например, чтобы отобразить счет и команды в заголовке)
url = f'https://api.api-sport.ru/v2/football/matches/{MATCH_ID}'
match = requests.get(url, headers={'Authorization': API_KEY}).json()
# Условные координаты ударов в нормированной системе 0..1
shots = np.array([
[0.8, 0.4],
[0.9, 0.5],
[0.7, 0.3],
[0.85, 0.6]
])
heatmap, xedges, yedges = np.histogram2d(shots[:, 0], shots[:, 1], bins=20, range=[[0, 1], [0, 1]])
plt.imshow(heatmap.T, origin='lower', cmap='hot', interpolation='nearest')
plt.title('Heatmap ударов')
plt.xlabel('Длина поля')
plt.ylabel('Ширина поля')
plt.colorbar(label='Интенсивность')
plt.show()
By combining such approaches with odds data from the oddsBase block and future AI modules on the service side, advanced analytical dashboards can be built. They will integrate the tactical picture on the field, betting market dynamics, and automatic model suggestions, making the combination of the sports events API and modern visualization stack a powerful tool for analysts, media, and betting projects.




