sportowe_wizualizacja/11tegen11 position map.ipynb
Koushik R Kirugulige 07ae7c489c
passmap showing average touch position
shows the average touch position of the 11 starting players
2019-06-19 10:15:57 +05:30

48 KiB

#edit only this tab
#give the folder path of the match
path = """C:\\\\Users\\\\Koushik\\\\Downloads\\\\open-data-master\\\\open-data-master\\\\data\\\\passmap\\\\ARGNIG\\\\"""
home_team = 'Argentina'
away_team = 'Nigeria'
import json
import os
import codecs
from pandas.io.json import json_normalize
import numpy as np
#import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.patches import Arc, Rectangle, ConnectionPatch
from matplotlib.offsetbox import  OffsetImage
#import squarify
from functools import reduce

Xg_req = pd.DataFrame(data=None)
for filename in (os.listdir(path)):
    #print(filename)
    
    with codecs.open("%s" % path + filename,encoding='utf-8') as data_file:    
        data = json.load(data_file)
        df = pd.DataFrame(data=None)
        
        df = json_normalize(data, sep = "_")
        
        #df =  df[(df['type_name'] == "Shot")]
        #df = df.loc[:,['location','shot_body_part_id','shot_end_location','shot_one_on_one','shot_technique_id','shot_type_id','under_pressure','shot_outcome_id']]
        #print(df.shape)
    Xg_req = Xg_req.append(df,ignore_index=True,sort=False)
        #df.drop(df.index, inplace=True)
        
print("done")
df = Xg_req
done
#type_id=30 is pass event AND type_id=19 is substitution event

pass_m = df.query('type_id == 30')
substitution = df.query('type_id == 19')
#pass_m = df.query('type_name == pass')
#this cell is WIP
substitution_home = set()
substitution_home = substitution[substitution.team_name == home_team]
substitution_home = substitution_home['substitution_replacement_name'].unique()
substitution_away = set()
substitution_away = substitution[substitution.team_name == away_team]
substitution_away = substitution_away['substitution_replacement_name'].unique()
print(substitution_away)
print(substitution_home)
['Odion Jude Ighalo' 'Alex Iwobi' 'Simeon Tochukwu Nwankwo']
['Cristian David Pavón' 'Maximiliano Eduardo Meza'
 'Sergio Leonel Agüero del Castillo']
# to get 

home_player = pass_m[(pass_m.team_name == home_team)] 
home_team_list = set()
home_team_list = home_player['player_name'].unique()
#print(substitution_belgium)
#belgium_list = [player for player in belgium_list if player not in substitution_belgium]
#belgium_list.remove([x for x in substitution_belgium])#belgium_list - substitution_belgium
home_player =pass_m['player_name'].isin(home_team_list)
pass_home = pass_m[home_player] #contains 11 players of home team

away_player = pass_m[(pass_m.team_name == away_team)] 
away_list = away_player['player_name'].unique()
#away_list = away_list - substitution_brazil
away_player = pass_m['player_name'].isin(away_list)
pass_away = pass_m[away_player]
#print(home_team_list)

#home_team_list = np.delete(home_team_list,substitution_home)
#print(home_team_list)
def draw_pitch(ax):
    # focus on only half of the pitch
    #Pitch Outline & Centre Line
    Pitch = Rectangle([0,0], width = 120, height = 80, fill = False)
    #Left, Right Penalty Area and midline
    LeftPenalty = Rectangle([0,22.3], width = 14.6, height = 35.3, fill = False)
    RightPenalty = Rectangle([105.4,22.3], width = 14.6, height = 35.3, fill = False)
    midline = ConnectionPatch([60,0], [60,80], "data", "data")

    #Left, Right 6-yard Box
    LeftSixYard = Rectangle([0,32], width = 4.9, height = 16, fill = False)
    RightSixYard = Rectangle([115.1,32], width = 4.9, height = 16, fill = False)


    #Prepare Circles
    centreCircle = plt.Circle((60,40),8.1,color="black", fill = False)
    centreSpot = plt.Circle((60,40),0.71,color="black")
    #Penalty spots and Arcs around penalty boxes
    leftPenSpot = plt.Circle((9.7,40),0.71,color="black")
    rightPenSpot = plt.Circle((110.3,40),0.71,color="black")
    leftArc = Arc((9.7,40),height=16.2,width=16.2,angle=0,theta1=310,theta2=50,color="black")
    rightArc = Arc((110.3,40),height=16.2,width=16.2,angle=0,theta1=130,theta2=230,color="black")
    
    element = [Pitch, LeftPenalty, RightPenalty, midline, LeftSixYard, RightSixYard, centreCircle, 
               centreSpot, rightPenSpot, leftPenSpot, leftArc, rightArc]
    for i in element:
        ax.add_patch(i)
players = home_team_list
#['Thibaut Courtois','Jan Vertonghen','Vincent Kompany','Toby Albertine Maurits Alderweireld','Thomas Meunier','Nacer Chadli','Axel Witsel','Marouane Fellaini-Bakkioui','Eden Hazard','Kevin De Bruyne','Romelu Lukaku Menama']
fig=plt.figure() #set up the figures

fig.set_size_inches(7, 5)
ax=fig.add_subplot(1,1,1)
draw_pitch(ax) #overlay our different objects on the pitch
plt.ylim(-2, 82)
plt.xlim(-2, 122)
plt.axis('off')
for player in players:
    x_avg = 0
    y_avg = 0
    if player not in substitution_home: 
        play_temp = pass_home[(pass_home.player_name == player)]
    #print(play_temp.location, players[player])
        for i in range(len(play_temp)):
            x_avg = x_avg + play_temp.iloc[i]['location'][0]
            y_avg = y_avg + play_temp.iloc[i]['location'][1]
        x_avg = x_avg/len(play_temp)
        y_avg = y_avg/len(play_temp)
    #print(x_avg,y_avg,players[player])
        ax.scatter(x_avg, y_avg, s=100)  
        ax.annotate(player.split()[0] +str(' ') + player.split()[-1], (x_avg, y_avg))
plt.show()
players = away_list #['Alisson Ramsés Becker','Fágner Conserva Lemos','Fernando Luiz Rosa','Gabriel Fernando de Jesus','João Miranda de Souza Filho','José Paulo Bezzera Maciel Júnior','Marcelo Vieira da Silva Júnior','Neymar da Silva Santos Junior','Philippe Coutinho Correia','Thiago Emiliano da Silva','Willian Borges da Silva']
fig=plt.figure() #set up the figures

fig.set_size_inches(7, 5)
ax=fig.add_subplot(1,1,1)
draw_pitch(ax) #overlay our different objects on the pitch
plt.ylim(-2, 82)
plt.xlim(-2, 122)
plt.axis('off')

for player in players:
    x_avg = 0
    y_avg = 0
    if player not in substitution_away:
    #print(players[player])
        play_temp = pass_away[(pass_away.player_name == player)]
    #print(play_temp.location, players[player])
        for i in range(len(play_temp)):
            x_avg = x_avg + play_temp.iloc[i]['location'][0]
            y_avg = y_avg + play_temp.iloc[i]['location'][1]
        x_avg = x_avg/len(play_temp)
        y_avg = y_avg/len(play_temp)
    #print(x_avg,y_avg,players[player])
        ax.scatter(x_avg, y_avg, s=150)  
        ax.annotate(player.split()[0] +str(' ') + player.split()[-1], (x_avg, y_avg))
plt.show()