def ind_heatmap(Df, player): from matplotlib.colors import LinearSegmentedColormap import cmasher as cmr #from mplsoccer import VerticalPitch df = Df.copy() pitch = Pitch(pitch_type='uefa', figsize=(10.5, 6.8), line_zorder=2, line_color='#636363', orientation='horizontal', constrained_layout=True, tight_layout=False, pitch_color='black') fig, ax = pitch.draw() df = df[df.name == player] touchdf = df[(df.isTouch == True) & (df.name == player)].reset_index() #pitch.kdeplot(touchdf.x, touchdf.y, ax=ax, cmap=cmap, #linewidths=0.3,fill=True,levels=1000) pitch.kdeplot(touchdf.x, touchdf.y, ax=ax, cmap=cmr.voltage, shade=True, levels=1000) ax.set_title(player + ' Touch-based heatmap', fontsize=25, color='white') fig.text(0.2, 0.0, "Created by Nikhil Rajesh / @nikhilrajesh231", fontstyle="italic", fontsize=15, color='black') fig.set_facecolor('black') ax.set_facecolor('black') return fig
def init_pitch(): pitch = Pitch(pitch_color=None, line_color='whitesmoke', stripe=False) fig, ax = pitch.draw() # SB coordinates start on the left side, so we should invert the axes ax.invert_yaxis() return fig, ax
def alineacion_442(valor_total, edad): try: valor_jugador = valor_total / 11 porteros = goalkeeper(1, valor_jugador, edad).reset_index() defensas = defenders(4, valor_jugador, edad).reset_index() medios = midfielders(4, valor_jugador, edad).reset_index() delanteros = forwards(2, valor_jugador, edad).reset_index() pitch = Pitch(pitch_color='grass', line_color='white', stripe=True) fig, ax = pitch.draw(figsize=(20, 20)) annotation = ax.annotate(porteros['short_name'][0], (5, 40), fontsize=40, ha='center') annotation = ax.annotate(defensas['short_name'][0], (24, 30), fontsize=40, ha='center') annotation = ax.annotate(defensas['short_name'][1], (24, 52), fontsize=40, ha='center') annotation = ax.annotate(defensas['short_name'][2], (32, 12), fontsize=40, ha='center') annotation = ax.annotate(defensas['short_name'][3], (32, 68), fontsize=40, ha='center') annotation = ax.annotate(medios['short_name'][0], (60, 30), fontsize=40, ha='center') annotation = ax.annotate(medios['short_name'][1], (60, 52), fontsize=40, ha='center') annotation = ax.annotate(medios['short_name'][2], (60, 12), fontsize=40, ha='center') annotation = ax.annotate(medios['short_name'][3], (60, 68), fontsize=40, ha='center') annotation = ax.annotate(delanteros['short_name'][0], (89, 24), fontsize=40, ha='center') annotation = ax.annotate(delanteros['short_name'][1], (89, 60), fontsize=40, ha='center') plt.savefig('output/images/442.jpg') result = pd.concat([porteros, defensas, medios, delanteros]).reset_index() result = result[[ 'short_name', 'nationality', 'position', 'age', 'wage_eur', 'value_eur', 'value_pred' ]] return result except: plt.savefig('output/images/442.jpg') return "No se han encontrado jugadores con esos parametros"
def show_buts(club_name): identifiant_club = df_2.loc[df_2['name'] == club_name, ['wyId']] identifiant_club = identifiant_club.iat[0,0] df_goals = df_4.loc[(df_4['teamId'] == identifiant_club) & (df_4['subEventName'] == 'Goal kick')] x, y = list(), list() for i in df_goals['positions']: x.append(i[1]['x']) y.append(i[1]['y']) pitch = Pitch(pitch_color='grass', line_color='white', stripe=True) fig, ax = pitch.draw() sc = pitch.scatter(y, x, s=100, ax=ax)
def turnovermap(Df,hometeam,homeid,awayteam,awayid): df = Df.copy() pitch = Pitch(pitch_type='statsbomb', figsize=(10,6), line_zorder=2, layout=(1,2), line_color='k', orientation='horizontal',constrained_layout=True, tight_layout=False) fig, ax = pitch.draw() homedef = df.query("(teamId==@homeid)&\ (type_displayName in ['Clearance','Tackle','Interception','Aerial','BlockedPass'])&\ (outcomeType_displayName=='Successful')") awaydef = df.query("(teamId==@awayid)&\ (type_displayName in ['Clearance','Tackle','Interception','Aerial','BlockedPass'])&\ (outcomeType_displayName=='Successful')") for i in homedef.index.tolist(): if(i<len(df)-1): if((df.teamId[i+1]==homeid)&(df.type_displayName[i+1] in ['BallRecovery','Pass','TakeOn'])& (df.outcomeType_displayName[i+1]=='Successful')): pitch.scatter(homedef.x[i],80-homedef.y[i],marker='o',s=50,zorder=5,facecolors='#082630', edgecolors='#fee090',linewidth=3,ax=ax[0]) for i in awaydef.index.tolist(): if(i<len(df)-1): if((df.teamId[i+1]==homeid)&(df.type_displayName[i+1] in ['BallRecovery','Pass','TakeOn'])& (df.outcomeType_displayName[i+1]=='Successful')): pitch.scatter(awaydef.x[i],80-awaydef.y[i],marker='o',s=50,zorder=5,facecolors='#082630', edgecolors='#fee090',linewidth=3,ax=ax[1]) ax[0].set_title(hometeam+'\n'+'Turnover creating'+'\n'+'Defensive activities',fontsize=30) ax[1].set_title(awayteam+'\n'+'Turnover creating'+'\n'+'Defensive activities',fontsize=30) fig.text(0.0, 0.0, "Created by Soumyajit Bose / @Soumyaj15209314",fontstyle="italic",fontsize=15,color='#edece9') fig.text(0.0, 0.05, "Turnover creating defensive activities include tackles, interceptions, aerials, clearances," +'\n'+" and blocked passes leading to winning possession",fontstyle="italic",fontsize=15,color='#edece9') # add_image(bu_alt, fig, left=0.9, bottom=0.01, width=0.07) return fig
def keypasses(Df,hometeam,homeid,awayteam,awayid): df = Df.copy() pitch = Pitch(pitch_type='statsbomb', figsize=(10,5), line_zorder=2, layout=(1,2), line_color='k', orientation='horizontal',constrained_layout=True, tight_layout=False) fig, ax = pitch.draw() homedef = df.query("(teamId==@homeid)&(KP == 1)&(endX!=0)&(endY!=0)") awaydef = df.query("(teamId==@awayid)&(KP == 1)&(endX!=0)&(endY!=0)") # homemask = homedef.outcomeType_displayName == 'Successful' # awaymask = awaydef.outcomeType_displayName == 'Successful' pitch.arrows(homedef.x,80-homedef.y,homedef.endX,80-homedef.endY,headwidth=5, headlength=5, zorder=5,color='#fee090',width=1,ax=ax[0]) # pitch.lines(homedef[~homemask].x,80-homedef[~homemask].y,homedef[~homemask].endX,80-homedef[~homemask].endY, # zorder=5,color='tab:red',linewidth=2,comet=True,ax=ax[0]) pitch.arrows(awaydef.x,80-awaydef.y,awaydef.endX,80-awaydef.endY,headwidth=5, headlength=5, zorder=5,color='#fee090',width=1,ax=ax[1]) # pitch.lines(awaydef[~awaymask].x,80-awaydef[~awaymask].y,awaydef[~awaymask].endX,80-awaydef[~awaymask].endY, # zorder=5,color='tab:red',linewidth=2,comet=True,ax=ax[1]) ax[0].set_title(hometeam+'\n'+'Key Passes',fontsize=30) ax[1].set_title(awayteam+'\n'+'Key Passes',fontsize=30) fig.text(0.0, 0.0, "Created by Soumyajit Bose / @Soumyaj15209314",fontstyle="italic",fontsize=15,color='#edece9') # add_image(bu_alt, fig, left=0.9, bottom=0.01, width=0.07) return fig
def badpasses(Df,hometeam,homeid): df = Df.copy() pitch = Pitch(pitch_type='statsbomb', figsize=(10,4.5), line_zorder=2, layout=(1,2), line_color='k', orientation='horizontal',constrained_layout=True, tight_layout=False) fig, ax = pitch.draw() def3rd = df.query("(teamId==@homeid)&(type_displayName == 'Pass')&(x<40)") mid3rd = df.query("(teamId==@homeid)&(type_displayName == 'Pass')&(x>=40)&(x<80)") defmask = def3rd.outcomeType_displayName == 'Successful' midmask = mid3rd.outcomeType_displayName == 'Successful' # awaymask = awaydef.outcomeType_displayName == 'Successful' pitch.arrows(def3rd[~defmask].x,80-def3rd[~defmask].y,def3rd[~defmask].endX,80-def3rd[~defmask].endY, headwidth=5, headlength=5,zorder=5,color='tab:red',width=1,ax=ax[0]) # pitch.lines(homedef[~homemask].x,80-homedef[~homemask].y,homedef[~homemask].endX,80-homedef[~homemask].endY, # zorder=5,color='tab:red',linewidth=2,comet=True,ax=ax[0]) pitch.arrows(mid3rd[~midmask].x,80-mid3rd[~midmask].y,mid3rd[~midmask].endX,80-mid3rd[~midmask].endY, headwidth=5, headlength=5,zorder=5,color='tab:red',width=1,ax=ax[1]) # pitch.lines(awaydef[~awaymask].x,80-awaydef[~awaymask].y,awaydef[~awaymask].endX,80-awaydef[~awaymask].endY, # zorder=5,color='tab:red',linewidth=2,comet=True,ax=ax[1]) ax[0].set_title(hometeam+' Unsuccessful Passes'+'\n'+'from defensive 3rd',fontsize=20) ax[1].set_title(hometeam+' Unsuccessful Passes'+'\n'+'from middle 3rd',fontsize=20) # fig.text(0.0, 0.05, "All unsuccessful passes originating from defensive third of the pitch",fontstyle="italic",fontsize=15,color='#edece9') fig.text(0.0, 0.0, "Created by Soumyajit Bose / @Soumyaj15209314",fontstyle="italic",fontsize=15,color='#edece9') # add_image(bu_alt, fig, left=0.9, bottom=0.0, width=0.07) return fig
def touchmap(Df,team,teamid): df = Df.copy() pitch = Pitch(pitch_type='statsbomb', figsize=(12,7), line_zorder=2, layout=(4,4), line_color='k', orientation='horizontal',constrained_layout=True, tight_layout=False) fig, ax = pitch.draw() touchdf = df[(df.isTouch==True)&(df.teamId==teamid)&(df.name!='')].reset_index() touchdf['y'] = 80 - touchdf['y'] players = touchdf.name.unique().tolist() Nplayers = len(players) for i in range(Nplayers): pdf = touchdf[touchdf.name==players[i]] bin_statistic = pitch.bin_statistic(pdf.x, pdf.y, statistic='count', bins=(25, 25)) bin_statistic['statistic'] = gaussian_filter(bin_statistic['statistic'], 1) pcm = pitch.heatmap(bin_statistic, ax=ax[i//4,i%4], cmap='Reds', edgecolors=None) ax[i//4,i%4].set_title(players[i],fontsize=15) for i in range(Nplayers,16): ax[i//4,i%4].remove() fig.text(0.0, 0.0, "Created by Soumyajit Bose / @Soumyaj15209314",fontstyle="italic",fontsize=15,color='#edece9') fig.text(0.3, 1.01, team+" Touch-based heatmaps",fontsize=25,color='#edece9') # add_image(bu_alt, fig, left=0.95, bottom=0.97, width=0.07) return fig
def progpassplotter(Df,team,teamid): pitch = Pitch(pitch_type='statsbomb', figsize=(12,10), line_zorder=2, layout=(4,4), view='full', line_color='#c7d5cc', orientation='horizontal',constrained_layout=True, tight_layout=False) fig, ax = pitch.draw() df = Df[(Df.teamId==teamid)&(Df.name!='')].reset_index() players = df.name.unique().tolist() Nplayers = len(players) for i in range(Nplayers): p = players[i] Passp = playerpasses(df,p) pitch.lines(Passp.x, Passp.y, Passp.endX, Passp.endY, transparent=True, lw=2, comet=True, color='#a1d76a',ax=ax[i//4,i%4]) ax[i//4,i%4].set_title(p,fontsize=15) for i in range(Nplayers,16): ax[i//4,i%4].remove() fig.text(0.05, -0.04, "Created by Soumyajit Bose / @Soumyaj15209314",fontstyle="italic",fontsize=15,color='#edece9') # add_image(bu_alt, fig, left=0.85, bottom=-0.07, width=0.05) fig_htext(s = "<Completed Progressive Passes> by all players of "+team, x = 0.1, y = 1, highlight_colors = ['#a1d76a'], highlight_weights=['bold'], string_weight='bold',fontsize=20,color='#edece9') return fig
def createShotmap(match_data, events_df, team, pitchcolor, shotcolor, goalcolor, titlecolor, legendcolor, marker_size): # getting team id and venue if match_data['home']['name'] == team: teamId = match_data['home']['teamId'] venue = 'home' else: teamId = match_data['away']['teamId'] venue = 'away' # getting opponent if venue == 'home': opponent = match_data['away']['name'] else: opponent = match_data['home']['name'] total_shots = events_df.loc[[9 in row for row in list(events_df['satisfiedEventsTypes'])]] team_shots = total_shots.loc[total_shots['teamId'] == teamId].reset_index(drop=True) mask_goal = team_shots.isGoal == True # Setup the pitch pitch = Pitch(pitch_type='statsbomb', orientation='vertical', pitch_color=pitchcolor, line_color='#c7d5cc', figsize=(16, 11), view='half', pad_top=2, tight_layout=True) fig, ax = pitch.draw() # Plot the goals pitch.scatter(team_shots[mask_goal].x/100*120, 80-team_shots[mask_goal].y/100*80, s=marker_size, edgecolors='black', c=goalcolor, zorder=2, label='goal', ax=ax) pitch.scatter(team_shots[~mask_goal].x/100*120, 80-team_shots[~mask_goal].y/100*80, edgecolors='white', c=shotcolor, s=marker_size, zorder=2, label='shot', ax=ax) # Set the title ax.set_title(f'{team} shotmap \n vs {opponent}', fontsize=30, color=titlecolor) # set legend leg = ax.legend(facecolor=pitchcolor, edgecolor='None', fontsize=20, loc='lower center', handlelength=4) leg_texts = leg.get_texts() # list of matplotlib Text instances. leg_texts[0].set_color(legendcolor) leg_texts[1].set_color(legendcolor) # Set the figure facecolor fig.set_facecolor(pitchcolor)
def defensesmap(Df,team,teamid): df = Df.copy() pitch = Pitch(pitch_type='statsbomb', figsize=(10,6), line_zorder=2, layout=(1,2), line_color='k', orientation='horizontal',constrained_layout=True, tight_layout=False) fig, ax = pitch.draw() defensedf = df.query("(type_displayName in ['Aerial','Clearance','Interception','Tackle','BlockedPass','Challenge'])\ &(teamId==@teamid)").reset_index() defensedf['defensive'] = [1 for i in range(len(defensedf))] for i in range(len(defensedf)): if(defensedf.loc[i,['type_displayName']][0]=='Aerial'): quals = defensedf.quals[i] if(286 in quals): defensedf.loc[i,['defensive']] = 0 if(defensedf.loc[i,['type_displayName']][0]=='Challenge'): quals = defensedf.quals[i] if(286 in quals): defensedf.loc[i,['defensive']] = 0 defensedf = defensedf[defensedf.defensive==1] defensedf['y'] = 80 - defensedf['y'] ppda = defensedf[defensedf.x>=48] ppda = ppda.query("type_displayName in ['Interception','Tackle','Challenge']") deepdf = defensedf[defensedf.x<48] bin_statistic = pitch.bin_statistic(ppda.x, ppda.y, statistic='count', bins=(25, 25)) bin_statistic['statistic'] = gaussian_filter(bin_statistic['statistic'], 1) pcm = pitch.heatmap(bin_statistic, ax=ax[0], cmap='Reds', edgecolors=None) ax[0].set_title(team+'\n'+' Pressurizing'+'\n'+ 'Defensive activities',fontsize=30) bin_statistic = pitch.bin_statistic(deepdf.x, deepdf.y, statistic='count', bins=(25, 25)) bin_statistic['statistic'] = gaussian_filter(bin_statistic['statistic'], 1) pcm = pitch.heatmap(bin_statistic, ax=ax[1], cmap='Reds', edgecolors=None) # cbar = fig.colorbar(pcm, ax=ax[1]) ax[1].set_title(team+'\n'+' Goal Protecting'+'\n'+'Defensive activities',fontsize=30) fig.text(0.0, 0.0, "Created by Soumyajit Bose / @Soumyaj15209314",fontstyle="italic",fontsize=15,color='#edece9') fig.text(0.0, 0.15, "Pressurizing defensive activities include tackles, interceptions and challenges"+'\n'+ "made high up in opposition territory",fontstyle="italic",fontsize=15,color='#edece9') fig.text(0.0, 0.05, "Goal protecting defensive activities include tackles, interceptions, defensive aerials, challenges," +'\n'+"clearances and blocked passes deep in own territory",fontstyle="italic",fontsize=15,color='#edece9') # add_image(bu_alt, fig, left=0.9, bottom=0.01, width=0.07) return fig
from mplsoccer.pitch import Pitch pitch = Pitch(pitch_color='grass', line_color='white', stripe=True, view='half') fig, ax = pitch.draw() ax.grid(True) fig.savefig('./soccer_ground.png', pad_inches=0, bbox_inches='tight')
df_false9 = df_false9.loc[df_false9.player_id == 5503, ['x', 'y']] df_before_false9 = df_before_false9.loc[df_before_false9.player_id == 5503, ['x', 'y']] ############################################################################## # View a dataframe df_false9.head() ############################################################################## # Plotting Messi's first game as a False-9 pitch = Pitch(pitch_type='statsbomb', figsize=(16, 11), pitch_color='grass', stripe=True, constrained_layout=False) fig, ax = pitch.draw() # plotting ax.set_title('The first Game Messi played in the false 9 role', fontsize=30, pad=20) # plot the kernel density estimation pitch.kdeplot(df_false9.x, df_false9.y, ax=ax, cmap='plasma', linewidths=3) # annotate pitch.annotate('6-2 thrashing \nof Real Madrid', (25, 10), color='white',
df_pass = df.loc[mask_team1, ['x', 'y', 'end_x', 'end_y', 'outcome_name']] mask_complete = df_pass.outcome_name.isnull() ############################################################################## # View the pass dataframe. df_pass.head() ############################################################################## # Plotting # Setup the pitch pitch = Pitch(pitch_type='statsbomb', orientation='horizontal', pitch_color='#22312b', line_color='#c7d5cc', figsize=(16, 11), constrained_layout=False, tight_layout=True) fig, ax = pitch.draw() # Plot the completed passes lc1 = pitch.lines(df_pass[mask_complete].x, df_pass[mask_complete].y, df_pass[mask_complete].end_x, df_pass[mask_complete].end_y, lw=5, transparent=True, comet=True, label='completed passes', color='#ad993c',
""" ============ Plot scatter ============ This example shows how to plot a scatter chart. """ from mplsoccer.pitch import Pitch import matplotlib.pyplot as plt plt.style.use('ggplot') pitch = Pitch(figsize=(10, 8)) fig, ax = pitch.draw() sc = pitch.scatter([70, 50, 20, 60, 90], [60, 50, 20, 10, 30], c=['red', 'blue', 'green', 'yellow', 'orange'], s=200, label='scatter', ax=ax) leg = ax.legend(borderpad=1, markerscale=0.5, labelspacing=1.5, loc='upper center', fontsize=15)
def passtypes(Df,team,teamid): df = Df.copy() # matchdict = Dict pitch = Pitch(pitch_type='statsbomb', figsize=(11,6), line_zorder=2, layout=(2,3), view='half', line_color='#c7d5cc', orientation='vertical',constrained_layout=True, tight_layout=False) fig, ax = pitch.draw() passdf = df.query("(type_displayName == 'Pass')&(outcomeType_displayName=='Successful')\ &(teamId==@teamid)").reset_index() passdf['y'] = 80 - passdf['y'] passdf['endY'] = 80 - passdf['endY'] progtocentre = passdf.query("(x<80)&(endX>80)&(endY>18)&(endY<62)")[['x','y','endX','endY']] wingplay = passdf.query("(x<80)&(endX>80)&((endY<18)or(endY>62))")[['x','y','endX','endY']] allbox = passdf.query("(endX>102)&(endY>18)&(endY<62)")[['x','y','endX','endY']] wingtobox = passdf.query("(x>80)&((y<18)or(y>62))&(endX>102)&(endY>18)&(endY<62)")[['x','y','endX','endY']] halfspaceplay = passdf.query("(x>80)&(((y>18)&(y<30))or((y>50)&(y<62)))&(endX>x)")[['x','y','endX','endY']] zone14play = passdf.query("(x>80)&(x<102)&(y>30)&(y<50)&(endX>x)")[['x','y','endX','endY']] pitch.lines(progtocentre.x, progtocentre.y, progtocentre.endX, progtocentre.endY, transparent=True, lw=2, comet=True, color='#a1d76a',ax=ax[0,0]) ax[0,0].set_title('Middle 3rd'+'\n'+'to Centre of final 3rd',fontsize=15) pitch.lines(wingplay.x, wingplay.y, wingplay.endX, wingplay.endY, transparent=True, lw=2, comet=True, color='#a1d76a',ax=ax[0,1]) ax[0,1].set_title('Middle 3rd'+'\n'+'to wing of final 3rd',fontsize=15) pitch.lines(allbox.x, allbox.y, allbox.endX, allbox.endY, transparent=True, lw=2, comet=True, color='#a1d76a',ax=ax[0,2]) ax[0,2].set_title('All passes to box',fontsize=15) pitch.lines(wingtobox.x, wingtobox.y, wingtobox.endX, wingtobox.endY, transparent=True, lw=2, comet=True, color='#a1d76a',ax=ax[1,0]) ax[1,0].set_title('Wing to box',fontsize=15) pitch.lines(halfspaceplay.x, halfspaceplay.y, halfspaceplay.endX, halfspaceplay.endY, transparent=True, lw=2, comet=True, color='#a1d76a',ax=ax[1,1]) ax[1,1].set_title('Attacking Passes'+'\n'+'From halfspace',fontsize=15) pitch.lines(zone14play.x, zone14play.y, zone14play.endX, zone14play.endY, transparent=True, lw=2, comet=True, color='#a1d76a',ax=ax[1,2]) ax[1,2].set_title('Attacking Passes'+'\n'+'From Zone 14',fontsize=15) fig.suptitle(team+' Progressive/Attacking Passes',fontsize=20) fig.text(0.05, -0.05, "Created by Soumyajit Bose / @Soumyaj15209314",fontstyle="italic",fontsize=15,color='#edece9') # add_image(bu_alt, fig, left=0.9, bottom=0.9, width=0.07) return fig
passes_between['width'] = passes_between.pass_count / passes_between.pass_count.max() * max_line_width average_locs_and_count['marker_size'] = (average_locs_and_count['count'] / average_locs_and_count['count'].max() * max_marker_size) ############################################################################## # Set color to make the lines more transparent when fewer passes are made min_transparency = 0.3 color = np.array(to_rgba('white')) color = np.tile(color, (len(passes_between), 1)) c_transparency = passes_between.pass_count / passes_between.pass_count.max() c_transparency = (c_transparency * (1 - min_transparency)) + min_transparency color[:, 3] = c_transparency ############################################################################## # Plotting pitch = Pitch(pitch_type='statsbomb', orientation='horizontal', pitch_color='#22312b', line_color='#c7d5cc', figsize=(16, 11), constrained_layout=True, tight_layout=False) fig, ax = pitch.draw() pass_lines = pitch.lines(passes_between.x, passes_between.y, passes_between.x_end, passes_between.y_end, lw=passes_between.width, color=color, zorder=1, ax=ax) pass_nodes = pitch.scatter(average_locs_and_count.x, average_locs_and_count.y, s=average_locs_and_count.marker_size, color='red', edgecolors='black', linewidth=1, alpha=1, ax=ax) for index, row in average_locs_and_count.iterrows(): pitch.annotate(row.name, xy=(row.x, row.y), c='white', va='center', ha='center', size=16, weight='bold', ax=ax) title = ax.set_title("{} {} Formation vs {}".format(team, formation, opponent), size=28, y=0.97, color='#c7d5cc') fig.set_facecolor("#22312b")
""" ===================== Plot football markers ===================== This example shows how to plot football markers. """ from mplsoccer.pitch import Pitch import matplotlib.pyplot as plt plt.style.use('ggplot') pitch = Pitch(figsize=(10, 8)) fig, ax = pitch.draw() # 'edgecolors' sets the color of the pentagons and edges, 'c' sets the color of the hexagons sc = pitch.scatter([70, 50], [60, 50], marker='football', label='football black and white', ax=ax) sc2 = pitch.scatter([20, 30], [10, 10], marker='football', s=2000, edgecolors='blue', c='yellow', label='football blue and yellow', ax=ax) sc3 = pitch.scatter([100, 20], [70, 70], marker='football', s=1500, edgecolors='green', c='red',
def switches(Df,hometeam,homeid,awayteam,awayid): df = Df.copy() pitch = Pitch(pitch_type='statsbomb', figsize=(10,5), line_zorder=2, layout=(1,2), line_color='k', orientation='horizontal',constrained_layout=True, tight_layout=False) fig, ax = pitch.draw() homedef = df.query("(teamId==@homeid)&(type_displayName == 'Pass')&((endY-y)**2>=1600.0)") awaydef = df.query("(teamId==@awayid)&(type_displayName == 'Pass')&((endY-y)**2>=1600.0)") homemask = homedef.outcomeType_displayName == 'Successful' awaymask = awaydef.outcomeType_displayName == 'Successful' pitch.lines(homedef[homemask].x,80-homedef[homemask].y,homedef[homemask].endX,80-homedef[homemask].endY, zorder=5,color='#fee090',linewidth=2,comet=True,ax=ax[0]) pitch.lines(homedef[~homemask].x,80-homedef[~homemask].y,homedef[~homemask].endX,80-homedef[~homemask].endY, zorder=5,color='tab:red',linewidth=2,comet=True,ax=ax[0]) pitch.lines(awaydef[awaymask].x,80-awaydef[awaymask].y,awaydef[awaymask].endX,80-awaydef[awaymask].endY, zorder=5,color='#fee090',linewidth=2,comet=True,ax=ax[1]) pitch.lines(awaydef[~awaymask].x,80-awaydef[~awaymask].y,awaydef[~awaymask].endX,80-awaydef[~awaymask].endY, zorder=5,color='tab:red',linewidth=2,comet=True,ax=ax[1]) ax[0].set_title(hometeam+'\n'+'Switches',fontsize=30) ax[1].set_title(awayteam+'\n'+'Switches',fontsize=30) fig.text(0.0, 0.0, "Created by Soumyajit Bose / @Soumyaj15209314",fontstyle="italic",fontsize=15,color='#edece9') fig.text(0.0, 0.05, "Red lines for unsuccessful switches, yellow for successful ones", fontstyle="italic",fontsize=15,color='#edece9') # add_image(bu_alt, fig, left=0.9, bottom=0.01, width=0.07) return fig
""" ================================== Event distribution using jointplot ================================== This example shows how to plot the location of events occurring in a match using a joint plot. """ from mplsoccer.pitch import Pitch from mplsoccer.statsbomb import read_event, EVENT_SLUG import os ############################################################################## # load the first game that Messi played as a false-9 kwargs = {'related_event_df': False, 'shot_freeze_frame_df': False, 'tactics_lineup_df': False, 'warn': False} df_false9 = read_event(f'{EVENT_SLUG}/69249.json', **kwargs)['event'] # filter messi's actions (starting positions) df_false9 = df_false9.loc[df_false9.player_id == 5503, ['x', 'y']] ############################################################################## # Plot the joint plot # Note that the axis of joint plots is always square, so here we make the pitch square by setting ``pad_left`` pitch = Pitch(pitch_type='statsbomb', pitch_color='grass', stripe=True, view='half', pad_left=20) joint_kws = {'shade': False, 'color': 'green', 'cmap': "plasma", 'linewidths': 3} g = pitch.jointplot(df_false9.x, df_false9.y, height=9, kind='kde', **joint_kws) g.fig.subplots_adjust(top=0.9) title = g.fig.suptitle("Messi's first game as a false 9", fontsize=25, ha='center', va='center')
import Metrica_Velocities as mvel import pandas as pd import numpy as np import matplotlib.pyplot as plt from mplsoccer.pitch import Pitch import statsmodels.api as sm import tensorflow as tf from tensorflow.keras import Sequential from tensorflow.keras.layers import Dense from tensorflow.keras.layers import LSTM from tensorflow.keras.layers import Dropout from tensorflow.keras.layers import BatchNormalization plt.style.use('ggplot') pitch = Pitch(pitch_color='#aabb97', line_color='white', stripe_color='#c2d59d', stripe=True) # optional stripes fig, ax = pitch.draw() # Reading data & cleaning data # set up initial path to data DATADIR = 'C:/Users/suhai/Desktop/All Folders/R Project/FootballAnalyticsCourse/LaurieOnTracking-master/tracking data' game_id = 2 # let's look at sample match 2 # read in the event data events = mio.read_event_data(DATADIR, game_id) # read in tracking data tracking_home = mio.tracking_data(DATADIR, game_id, 'Home') tracking_away = mio.tracking_data(DATADIR, game_id, 'Away')
import json match_id = 7581 with open('E:/SoccermaticsForPython-master/statsbomb/data/events/' + str(match_id) + '.json') as f: data = json.load(f) from pandas import json_normalize df = json_normalize(data, sep="_").assign(match_id=str(match_id) + '.json'[:-5]) Passes = df.loc[df['type_name'] == 'Pass'].set_index('id') from mplsoccer.pitch import Pitch pitch = Pitch(pitch_type='statsbomb', pitch_color='#22312b', line_color='#c7d5cc', figsize=(16, 11), constrained_layout=True, tight_layout=False) fig, ax = pitch.draw() fig.set_facecolor('#22312b') for i, pas in Passes.iterrows(): x = pas['location'][0] y = pas['location'][1] endx = pas['pass_end_location'][0] endy = pas['pass_end_location'][1] name = pas['player_name'] == 'Virgil van Dijk' if name: pitch.scatter(x, y, ax=ax,
plt.style.use('dark_background') fig, axes = plt.subplots(4, 2, figsize=(12, 14)) axes = axes.ravel() pitch_kwargs = {'line_color': '#94A7AE', 'axis': True, 'label': True, 'pad_left': 0, 'pad_right': 0, 'pad_top': 0, 'pad_bottom': 0, 'linewidth': 1} pitch_types = ['statsbomb', 'statsperform', 'tracab', 'wyscout', 'metricasports', 'opta', 'stats'] fontcolor = '#b6b9ea' arrowprops = {'arrowstyle': '->', 'lw': 4, 'connectionstyle': 'angle3,angleA=0,angleB=-90', 'color': fontcolor} font_kwargs = {'fontsize': 14, 'ha': 'center', 'va': 'bottom', 'fontweight': 'bold', 'fontstyle': 'italic', 'c': fontcolor} for idx, pt in enumerate(pitch_types): if pt in ['tracab', 'metricasports']: pitch = Pitch(pitch_type=pt, pitch_length=105, pitch_width=68, **pitch_kwargs) else: pitch = Pitch(pitch_type=pt, **pitch_kwargs) pitch.draw(axes[idx]) xmin, xmax, ymin, ymax = pitch.extent if pitch.aspect != 1: text = 'data coordinates \n are square (1:1) \n scale up to a real-pitch size' axes[idx].annotate(text, xy=(xmin, ymin), xytext=(0 + (xmax - xmin)/2, ymin), **font_kwargs) axes[idx].xaxis.set_ticks([xmin, xmax]) axes[idx].yaxis.set_ticks([ymin, ymax]) axes[idx].tick_params(labelsize=15) axes[idx].set_title(pt, fontsize=30, c='#9749b9', pad=15) if pitch.invert_y: text = 'inverted y axis' if pt == 'stats':
""" ============== mplsoccer logo ============== """ import matplotlib.pyplot as plt from mplsoccer.pitch import Pitch from matplotlib import rcParams plt.style.use('ggplot') plt.xkcd() # plot the mplsoccer logo pitch = Pitch(pitch_color='grass', stripe=True, figsize=(1280 / rcParams['figure.dpi'], 640 / rcParams['figure.dpi']), pad_left=8, pad_top=8, pad_bottom=8, pad_right=8) fig, ax = pitch.draw() annotation = ax.annotate('mplsoccer', (60, 40), fontsize=120, ha='center', va='center')
def takeonmap(Df,hometeam,homeid,awayteam,awayid): df = Df.copy() pitch = Pitch(pitch_type='statsbomb', figsize=(10,5), line_zorder=2, layout=(1,2), line_color='k', orientation='horizontal',constrained_layout=True, tight_layout=False) fig, ax = pitch.draw() homedef = df.query("(teamId==@homeid)&(type_displayName == 'TakeOn')") awaydef = df.query("(teamId==@awayid)&(type_displayName == 'TakeOn')") homemask = homedef.outcomeType_displayName == 'Successful' awaymask = awaydef.outcomeType_displayName == 'Successful' pitch.scatter(homedef[homemask].x,80-homedef[homemask].y,marker='o',s=50,zorder=5,facecolors='#082630', edgecolors='#fee090',linewidth=3,ax=ax[0]) pitch.scatter(homedef[~homemask].x,80-homedef[~homemask].y,marker='o',s=50,zorder=5,facecolors='#082630', edgecolors='tab:red',linewidth=3,ax=ax[0]) pitch.scatter(awaydef[awaymask].x,80-awaydef[awaymask].y,marker='o',s=50,zorder=5,facecolors='#082630', edgecolors='#fee090',linewidth=3,ax=ax[1]) pitch.scatter(awaydef[~awaymask].x,80-awaydef[~awaymask].y,marker='o',s=50,zorder=5,facecolors='#082630', edgecolors='tab:red',linewidth=3,ax=ax[1]) ax[0].set_title(hometeam+'\n'+'TakeOns',fontsize=30) ax[1].set_title(awayteam+'\n'+'TakeOns',fontsize=30) fig.text(0.0, 0.0, "Created by Soumyajit Bose / @Soumyaj15209314",fontstyle="italic",fontsize=15,color='#edece9') fig.text(0.0, 0.05, "Red markers for unsuccessful takeons, yellow for successful ones", fontstyle="italic",fontsize=15,color='#edece9') # add_image(bu_alt, fig, left=0.9, bottom=0.01, width=0.07) return fig
""" from urllib.request import urlopen from PIL import Image import matplotlib.pyplot as plt from mplsoccer.pitch import Pitch from mplsoccer.utils import add_image # opening the background image # pic by webtreats: https://www.flickr.com/photos/webtreatsetc/ # available at: https://www.flickr.com/photos/webtreatsetc/5756834840 IMAGE_URL = 'https://live.staticflickr.com/5065/5756834840_e31c559b26_c_d.jpg' image = Image.open(urlopen(IMAGE_URL)) pitch = Pitch(pitch_color='None') fig, ax = pitch.draw(tight_layout=False) # adding the image and the image credits ax_image = add_image(image, fig, left=0, bottom=0, width=1, height=1) ax.text(70, 75, 'cloud pic by\nwebtreats (flickr)', color='white') # set the pitch to be plotted after the image # note these numbers can be anything like 0.5, 0.2 as long # as the image zorder is behind the pitch zorder ax.set_zorder(1) ax_image.set_zorder(0) # save with 'tight' and no padding to avoid borders # fig.savefig('cloud.png', bbox_inches='tight', pad_inches=0) plt.show() # If you are using a Jupyter notebook you do not need this line
'shot_freeze_frame_df': False, 'tactics_lineup_df': False, 'warn': False } df_false9 = read_event(f'{EVENT_SLUG}/69249.json', **kwargs)['event'] df_before_false9 = read_event(f'{EVENT_SLUG}/69251.json', **kwargs)['event'] # filter messi's actions (starting positions) df_false9 = df_false9.loc[df_false9.player_id == 5503, ['x', 'y']] df_before_false9 = df_before_false9.loc[df_before_false9.player_id == 5503, ['x', 'y']] ############################################################################## # plotting pitch = Pitch(pitch_type='statsbomb', figsize=(16, 9), layout=(1, 2), pitch_color='#22312b', stripe=False, line_zorder=2) fig, ax = pitch.draw() pitch.hexbin(df_before_false9.x, df_before_false9.y, gridsize=10, ax=ax[0], cmap='Blues') pitch.hexbin(df_false9.x, df_false9.y, gridsize=10, ax=ax[1], cmap='Blues') title1 = ax[0].set_title( 'Messi in the game directly before \n playing in the false 9 role', fontsize=25, pad=20) title2 = ax[1].set_title('The first Game Messi \nplayed in the false 9 role', fontsize=25,
def passmap(Df,teamname,teamid,min1,max1): pitch = Pitch(pitch_type='statsbomb', figsize=(20,13), line_zorder=2, line_color='#c7d5cc', orientation='horizontal',constrained_layout=True, tight_layout=False) fig, ax = pitch.draw() df = Df.copy() df = df[(df.expandedMinute>=min1)&(df.expandedMinute<=max1)] allplayers = df[(df.teamId==teamid)&(df.name!='')].name.tolist() playersubbedoff = df[(df.type_displayName == 'SubstitutionOff')&(df.teamId==teamid)]['name'].tolist() timeoff = df[(df.type_displayName == 'SubstitutionOff')&(df.teamId==teamid)]['expandedMinute'].tolist() playersubbedon = df[(df.type_displayName == 'SubstitutionOn')&(df.teamId==teamid)]['name'].tolist() timeon = df[(df.type_displayName == 'SubstitutionOn')&(df.teamId==teamid)]['expandedMinute'].tolist() majoritylist = [] minoritylist = [] for i in range(len(timeon)): if((timeon[i]>=min1)&(timeon[i]<=max1)): player1min = timeon[i] - min1 player2min = max1 - timeon[i] if(player1min >= player2min): majoritylist.append(playersubbedoff[i]) minoritylist.append(playersubbedon[i]) else: majoritylist.append(playersubbedon[i]) minoritylist.append(playersubbedoff[i]) players = list(set(allplayers) - set(minoritylist)) # return players shirtNo = [] for p in players: shirtNo.append(int(df[df.name==p]['shirtNo'].values[0])) passdf = df.query("(type_displayName=='Pass')&(name in @players)&(receiver in @players)&\ (outcomeType_displayName == 'Successful')&(teamId==@teamid)") passdf['x'] = passdf['x'] passdf['y'] = 80 - passdf['y'] passdf['endX'] = passdf['endX'] passdf['endY'] = 80 - passdf['endY'] cols = ['name','receiver'] gamedf = passdf[cols] totalpassdf = gamedf.groupby(cols).size().reset_index(name="count") totalpassdf[cols] = np.sort(totalpassdf[cols],axis=1) totalpassdf = totalpassdf.groupby(cols)['count'].agg(['sum']).reset_index() avg_x = [] avg_y = [] blank=np.zeros(len(totalpassdf)) totalpassdf['passer_x'] = blank totalpassdf['passer_y'] = blank totalpassdf['receiver_x'] = blank totalpassdf['receiver_y'] = blank uniquenames = np.array(players) uniquejerseys = np.array(shirtNo) totalpasses = [] for name in uniquenames: player_pass_df = passdf.query("(name == @name)") x = np.mean(player_pass_df['x']) y = np.mean(player_pass_df['y']) totalpasses.append(len(player_pass_df)) avg_x.append(x) avg_y.append(y) for i in range(len(totalpassdf)): passername = totalpassdf.iloc[i,0] receivername = totalpassdf.iloc[i,1] totalpassdf.iloc[i,3] = avg_x[np.where(uniquenames==passername)[0][0]] totalpassdf.iloc[i,4] = avg_y[np.where(uniquenames==passername)[0][0]] totalpassdf.iloc[i,5] = avg_x[np.where(uniquenames==receivername)[0][0]] totalpassdf.iloc[i,6] = avg_y[np.where(uniquenames==receivername)[0][0]] link = totalpassdf.iloc[i,2] passerx = totalpassdf.iloc[i,3] receiverx = totalpassdf.iloc[i,5] passery = totalpassdf.iloc[i,4] receivery = totalpassdf.iloc[i,6] if(link>=1): ax.plot([passerx, receiverx],[passery, receivery],linewidth=link/2.5, color ='lightgrey') for indx in range(len(uniquenames)): name = uniquenames[indx] size = 50*totalpasses[np.where(uniquenames==name)[0][0]] avgx = avg_x[np.where(uniquenames==name)[0][0]] avgy = avg_y[np.where(uniquenames==name)[0][0]] jersey = shirtNo[np.where(uniquenames==name)[0][0]] ax.scatter(avgx,avgy,color='#d7191c',s=1000,zorder=3) ax.annotate(jersey, (avgx, avgy),alpha=1,fontsize=25,color='w', horizontalalignment='center', verticalalignment='center').set_path_effects([path_effects.Stroke(linewidth=2, foreground='black'), path_effects.Normal()]) ax.text(125,3,'# Player (Acc passes)',fontsize=25) for i in range(12): ax.text(127,3+4*i,'|',fontsize=50) for i in range(30): ax.text(125+i,3.5,'_',fontsize=50) # ax.plot([126,3],[126,50]) for indx in range(len(players)): ax.text(125,7+4*indx,str(shirtNo[indx]),fontsize=25) for indx in range(len(players)): ax.text(130,7+4*indx,players[indx]+'('+str(totalpasses[indx])+')',fontsize=25) ax.set_title(teamname+' Passmap, Exp. Minutes '+str(min1)+ " to "+str(max1),fontsize=50) fig.text(0.02, 0.05, "Created by Soumyajit Bose / @Soumyaj15209314",fontstyle="italic",fontsize=20,color='#edece9') fig.text(0.02, -0.05, "Acc passes mentioned in brackets next to player names "+"\n" "Width of line is proportional to number of passes exchanged between two players"+"\n"+ "A minimum of 1 pass need to be exchanged to show up as a line", fontstyle="italic",fontsize=25,color='#edece9') # add_image(bu_alt, fig, left=0.9, bottom=-0.05, width=0.07) return fig
df_total = df_total.T df_total = df_total.divide(df_total.sum(axis=1), axis=0) * 100 ############################################################################## # Calculate the percentages for each team and sort so that the teams which press higher are last df[pressure_cols] = df[pressure_cols].divide(df[pressure_cols].sum(axis=1), axis=0) * 100. df.sort_values(['Att 3rd', 'Def 3rd'], ascending=[True, False], inplace=True) ############################################################################## # Plot the percentages # setup a mplsoccer pitch pitch = Pitch(line_zorder=2, line_color='black', figsize=(16, 9), layout=(4, 5), tight_layout=False, constrained_layout=True) # mplsoccer calculates the binned statistics usually from raw locations, such as pressure events # for this example we will create a binned statistic dividing the pitch into thirds for one point (0, 0) # we will fill this in a loop later with each team's statistics from the dataframe bin_statistic = pitch.bin_statistic([0], [0], statistic='count', bins=(3, 1)) # load the StatsBomb logo sb_logo = Image.open( urlopen(( 'https://github.com/statsbomb/open-data/blob/fb54bd7fe20dbd5299fafc64f1f6f0d919a5e40d/' 'stats-bomb-logo.png?raw=true'))) # Plot
# -*- coding: utf-8 -*- """ Created on Fri Sep 17 01:24:28 2021 @author: dev """ import json match_id = 22912 with open('E:/SoccermaticsForPython-master/statsbomb/data/events/'+str(match_id)+'.json') as f: data = json.load(f) from pandas import json_normalize df = json_normalize(data, sep = "_").assign(match_id = str(match_id)+'.json'[:-5]) Passes = df.loc[df['type_name'] == 'Pass'].set_index('id') from mplsoccer.pitch import Pitch pitch = Pitch(pitch_type='statsbomb', pitch_color='w', line_color='#c7d5cc' ,figsize=(16, 11),constrained_layout=True, tight_layout=False ) fig, ax = pitch.draw() fig.set_facecolor('#22312b')