Problem With Friends Of Tracking Code Noob [python]
I am learning with python code and I have some issues: https://github.com/Slothfulwave612/Football-Analytics-Using-Python/blob/master/03.%20Analyzing%20Event%20Data/pass_map.py My
Solution 1:
So it's combining all the matches onto 1 because the figure is "drawing" on top of the previous one. There's a few other things you need to change too.
- The away team will not always be Real Madrid, so make that dynamic
- Adjust that in the figure text text so it's not always "
vs. Real Madrid"
- Save the file as something dynamic so they don't overwrite
- Instead of doing
plt.text
to put in the titles (which is fine if you want to annotate at a specific x,y coordinates), useplt.title()
andplt.suptitle()
. It'll center and just make it a nicer layout of the text - You us
i
for you match id variable when iterating, but then you don't change/include that in the loop - This is the main issue:
(fig,ax) = createPitch(pitch_length_X, pitch_width_Y,'yards','gray')
is what is creating your "blank canvas" to plot on. So this needs to be called before each plot. It's like grabbing a new blank sheet of paper to draw on. If you just use the first initial sheet, then everything will go on that 1 sheet. So move that into your for loop
Code
import matplotlib.pyplot as plt
import json
from pandas.io.json import json_normalize
from FCPython import createPitch
## Note Statsbomb data uses yards for their pitch dimensions
pitch_length_X = 120
pitch_width_Y = 80## match id for our El Clasico
match_list = [16205, 16131, 16265]
teamA = 'Barcelona'#<--- adjusted herefor match_id in match_list:
## calling the function to create a pitch map## yards is the unit for measurement and## gray will be the line color of the pitch map
(fig,ax) = createPitch(pitch_length_X, pitch_width_Y,'yards','gray') #< moved into for loop
player_name = 'Lionel Andrés Messi Cuccittini'## this is the name of our event data file for## our required El Clasico
file_name = str(match_id) + '.json'## loading the required event data file
my_data = json.load(open('Statsbomb/data/events/' + file_name, 'r', encoding='utf-8'))
## get the nested structure into a dataframe ## store the dataframe in a dictionary with the match id as key
df = json_normalize(my_data, sep='_').assign(match_id = file_name[:-5])
teamB = [x for x inlist(df['team_name'].unique()) if x != teamA ][0] #<--- get other team name## making the list of all column names
column = list(df.columns)
## all the type names we have in our dataframe
all_type_name = list(df['type_name'].unique())
## creating a data frame for pass## and then removing the null values## only listing the player_name in the dataframe
pass_df = df.loc[df['type_name'] == 'Pass', :].copy()
pass_df.dropna(inplace=True, axis=1)
pass_df = pass_df.loc[pass_df['player_name'] == player_name, :]
## creating a data frame for ball receipt## removing all the null values## and only listing Barcelona players in the dataframe
breceipt_df = df.loc[df['type_name'] == 'Ball Receipt*', :].copy()
breceipt_df.dropna(inplace=True, axis=1)
breceipt_df = breceipt_df.loc[breceipt_df['team_name'] == 'Barcelona', :]
pass_comp, pass_no = 0, 0## pass_comp: completed pass## pass_no: unsuccessful pass## iterating through the pass dataframefor row_num, passed in pass_df.iterrows():
if passed['player_name'] == player_name:
## for away side
x_loc = passed['location'][0]
y_loc = passed['location'][1]
pass_id = passed['id']
summed_result = sum(breceipt_df.iloc[:, 14].apply(lambda x: pass_id in x))
if summed_result > 0:
## if pass made was successful
color = 'blue'
label = 'Successful'
pass_comp += 1else:
## if pass made was unsuccessful
color = 'red'
label = 'Unsuccessful'
pass_no += 1## plotting circle at the player's position
shot_circle = plt.Circle((pitch_length_X - x_loc, y_loc), radius=2, color=color, label=label)
shot_circle.set_alpha(alpha=0.2)
ax.add_patch(shot_circle)
## parameters for making the arrow
pass_x = 120 - passed['pass_end_location'][0]
pass_y = passed['pass_end_location'][1]
dx = ((pitch_length_X - x_loc) - pass_x)
dy = y_loc - pass_y
## making an arrow to display the pass
pass_arrow = plt.Arrow(pitch_length_X - x_loc, y_loc, -dx, -dy, width=1, color=color)
## adding arrow to the plot
ax.add_patch(pass_arrow)
## computing pass accuracy
pass_acc = (pass_comp / (pass_comp + pass_no)) * 100
pass_acc = str(round(pass_acc, 2))
## adding text to the plot
plt.suptitle('{} pass map vs {}'.format(player_name, teamB), fontsize=15) #<-- make dynamic and change to suptitle
plt.title('Pass Accuracy: {}'.format(pass_acc), fontsize=15) #<-- change to title## handling labels
handles, labels = plt.gca().get_legend_handles_labels()
by_label = dict(zip(labels, handles))
plt.legend(by_label.values(), by_label.keys(), loc='best', bbox_to_anchor=(0.9, 1, 0, 0), fontsize=12)
## editing the figure size and saving it
fig.set_size_inches(12, 8)
fig.savefig('{} passmap.png'.format(match_id), dpi=200) #<-- dynamic file name## showing the plot
plt.show()
Post a Comment for "Problem With Friends Of Tracking Code Noob [python]"