예제 #1
0
# get data for a Sevilla versus Barcelona match with a high amount of shots
kwargs = {
    'related_event_df': False,
    'shot_freeze_frame_df': False,
    'tactics_lineup_df': False,
    'warn': False
}
df = read_event(f'{EVENT_SLUG}/9860.json', **kwargs)['event']

# setup the mplsoccer StatsBomb Pitches
# note not much padding around the pitch so the marginal axis are tight to the pitch
# if you are using a different goal type you will need to increase the padding to see the goals
pitch = Pitch(pad_top=0.05,
              pad_right=0.05,
              pad_bottom=0.05,
              pad_left=0.05,
              line_zorder=2)
vertical_pitch = VerticalPitch(half=True,
                               pad_top=0.05,
                               pad_right=0.05,
                               pad_bottom=0.05,
                               pad_left=0.05,
                               line_zorder=2)

# setup a mplsoccer FontManager to download google fonts (Roboto-Regular / SigmarOne-Regular)
fm = FontManager()
fm_rubik = FontManager(
    ('https://github.com/google/fonts/blob/main/ofl/rubikmonoone/'
     'RubikMonoOne-Regular.ttf?raw=true'))
예제 #2
0
##############################################################################
# Boolean mask for filtering the dataset by team

team1, team2 = df.team_name.unique()
mask_team1 = (df.type_name == 'Pass') & (df.team_name == team1)

##############################################################################
# Filter dataset to only include one teams passes and get boolean mask for the completed passes

df_pass = df.loc[mask_team1, ['x', 'y', 'end_x', 'end_y', 'outcome_name']]
mask_complete = df_pass.outcome_name.isnull()

##############################################################################
# Setup the pitch and number of bins
pitch = Pitch(pitch_type='statsbomb',
              line_zorder=2,
              line_color='#c7d5cc',
              pitch_color='#22312b')
bins = (6, 4)

##############################################################################
# Plotting using a single color and length
fig, ax = pitch.draw(figsize=(16, 11),
                     constrained_layout=True,
                     tight_layout=False)
# plot the heatmap - darker colors = more passes originating from that square
bs_heatmap = pitch.bin_statistic(df_pass.x,
                                 df_pass.y,
                                 statistic='count',
                                 bins=bins)
hm = pitch.heatmap(bs_heatmap, ax=ax, cmap='Blues')
# plot the pass flow map with a single color ('black') and length of the arrow (5)
예제 #3
0
##############################################################################
# Rotated markers
# ---------------
# I also included a method for rotating markers in mplsoccer.
#
# Warning: The rotation angle is in degrees and assumes the original marker is pointing upwards ↑.
# If it's not you will have to modify the rotation degrees.
# Rotates the marker in degrees, clockwise. 0 degrees is facing the
# direction of play (left to right).
# In a horizontal pitch, 0 degrees is this way →, in a vertical pitch, 0 degrees is this way ↑
#
# We are going to plot pass data as an arrowhead marker with the
# arrow facing in the direction of the pass
# The marker size is going to relate to the pass distance,
# so larger markers mean the pass was longer.
pitch = Pitch()
fig, ax = pitch.draw(figsize=(14, 12))
angle, distance = pitch.calculate_angle_and_distance(df_pass_barca.x,
                                                     df_pass_barca.y,
                                                     df_pass_barca.end_x,
                                                     df_pass_barca.end_y,
                                                     standardized=False,
                                                     degrees=True)
sc = pitch.scatter(
    df_pass_barca.x,
    df_pass_barca.y,
    rotation_degrees=angle,
    c='#b94b75',  # color for scatter in hex format
    edgecolors='#383838',
    alpha=0.9,
    s=(distance / distance.max()) * 900,
예제 #4
0
# Get the StatsBomb logo and Fonts

LOGO_URL = 'https://raw.githubusercontent.com/statsbomb/open-data/master/img/statsbomb-logo.jpg'
sb_logo = Image.open(urlopen(LOGO_URL))

# a FontManager object for using a google font (default Robotto)
fm = FontManager()
# path effects
path_eff = [path_effects.Stroke(linewidth=3, foreground='black'),
            path_effects.Normal()]

##############################################################################
# Plot the percentages

# setup a mplsoccer pitch
pitch = Pitch(line_zorder=2, line_color='black', pad_top=20)

# 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))

GRID_HEIGHT = 0.8
CBAR_WIDTH = 0.03
fig, axs = pitch.grid(nrows=4, ncols=5, figheight=20,
                      # leaves some space on the right hand side for the colorbar
                      grid_width=0.88, left=0.025,
                      endnote_height=0.06, endnote_space=0,
                      # Turn off the endnote/title axis. I usually do this after
                      # I am happy with the chart layout and text placement
예제 #5
0
df_total = pd.DataFrame(df[pressure_cols].sum())
df_total.columns = ['total']
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')

# 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))

# Plot
fig, axes = pitch.draw(figsize=(16, 9),
                       ncols=5,
                       nrows=4,
                       tight_layout=False,
                       constrained_layout=True)
axes = axes.ravel()
teams = df['Squad'].values
예제 #6
0
    'related_event_df': False,
    'shot_freeze_frame_df': False,
    'tactics_lineup_df': False,
    'warn': False
}
df = pd.concat([
    read_event(f'{EVENT_SLUG}/{file}', **kwargs)['event']
    for file in match_files
])
# filter chelsea pressure events
mask_chelsea_pressure = (df.team_name == 'Chelsea FCW') & (df.type_name
                                                           == 'Pressure')
df = df.loc[mask_chelsea_pressure, ['x', 'y']]

##############################################################################
# Plot the heatmaps

# setup pitch
pitch = Pitch(pitch_type='statsbomb', line_zorder=2, line_color='white')
# draw
fig, ax = pitch.draw(figsize=(16, 9))
bin_statistic = pitch.bin_statistic(df.x,
                                    df.y,
                                    statistic='count',
                                    bins=(25, 25))
bin_statistic['statistic'] = gaussian_filter(bin_statistic['statistic'], 1)
pcm = pitch.heatmap(bin_statistic, ax=ax, cmap='hot', edgecolors='#22312b')
cbar = fig.colorbar(pcm, ax=ax)
TITLE_STR = 'Location of pressure events - 3 home games for Chelsea FC Women'
title = fig.suptitle(TITLE_STR, x=0.4, y=0.98, fontsize=23)
예제 #7
0
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']
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',
              pitch_color='#22312b',
              stripe=False,
              line_zorder=2)
fig, ax = pitch.draw(
    figsize=(16, 9),
    nrows=1,
    ncols=2,
)
pitch.hexbin(df_before_false9.x, df_before_false9.y, ax=ax[0], cmap='Blues')
pitch.hexbin(df_false9.x, df_false9.y, ax=ax[1], cmap='Blues')
TITLE_STR1 = 'Messi in the game directly before \n playing in the false 9 role'
TITLE_STR2 = 'The first Game Messi \nplayed in the false 9 role'
title1 = ax[0].set_title(TITLE_STR1, fontsize=25, pad=20)
title2 = ax[1].set_title(TITLE_STR2, fontsize=25, pad=20)
fig = plt.figure(figsize=FIGSIZE)

fm_rubik = FontManager(('https://github.com/google/fonts/blob/main/ofl/rubikmonoone/'
                        'RubikMonoOne-Regular.ttf?raw=true'))

# layout specifications
PAD = 1
pitch_spec = {'pad_left': PAD, 'pad_right': PAD,
              'pad_bottom': PAD, 'pad_top': PAD, 'pitch_color': 'None'}
pitch_width, pitch_length = 80, 105
pitch_width3, pitch_length3 = 60, 105
pitch_length4, pitch_width4 = 120, 68
pitch_length6, pitch_width6 = 85, 68

# define pitches (top left, top middle, top right, bottom left, bottom middle, bottom right)
pitch1 = Pitch(pitch_type='custom', pitch_width=pitch_width, pitch_length=pitch_length,
               line_color='#b94e45', **pitch_spec)
pitch2 = Pitch(pitch_type='statsbomb', **pitch_spec)
pitch3 = Pitch(pitch_type='custom', pitch_width=pitch_width3, pitch_length=pitch_length3,
               line_color='#56ae6c', **pitch_spec)
pitch4 = VerticalPitch(pitch_type='custom', pitch_length=pitch_length4, pitch_width=pitch_width4,
                       line_color='#bc7d39', **pitch_spec)
pitch5 = VerticalPitch(pitch_type='statsbomb', **pitch_spec)
pitch6 = VerticalPitch(pitch_type='custom', pitch_length=pitch_length6, pitch_width=pitch_width6,
                       line_color='#677ad1', **pitch_spec)

TITLE_HEIGHT = 0.1  # title axes are 10% of the figure height

#  width of pitch axes as percent of the figure width
TOP_WIDTH = 0.27
BOTTOM_WIDTH = 0.18
예제 #9
0
import matplotlib.pyplot as plt

# read data
df = read_event(f'{EVENT_SLUG}/7478.json',
                related_event_df=False,
                shot_freeze_frame_df=False,
                tactics_lineup_df=False)['event']

##############################################################################
# Filter passes by Jodie Taylor
df = df[(df.player_name == 'Jodie Taylor') & (df.type_name == 'Pass')].copy()

##############################################################################
# Plotting

pitch = Pitch()
fig, ax = pitch.draw(figsize=(8, 6))
hull = pitch.convexhull(df.x, df.y)
poly = pitch.polygon(hull,
                     ax=ax,
                     edgecolor='cornflowerblue',
                     facecolor='cornflowerblue',
                     alpha=0.3)
scatter = pitch.scatter(df.x,
                        df.y,
                        ax=ax,
                        edgecolor='black',
                        facecolor='cornflowerblue')
plt.show(
)  # if you are not using a Jupyter notebook this is necessary to show the plot
예제 #10
0
    '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', 'custom', 'skillcorner']:
        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.dim.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)
    if pt == 'skillcorner':
예제 #11
0
# I created a function to calculate the maximum dimensions you can get away with while
# having a set figure size. Let's use this to create the largest pitch possible
# with a 16:9 figure aspect ratio.

FIGWIDTH = 16
FIGHEIGHT = 9
NROWS = 1
NCOLS = 1
# here we want the maximum side in proportion to the figure dimensions
# (height in this case) to take up all of the image
MAX_GRID = 1

# pitch with minimal padding (2 each side)
pitch = Pitch(pad_top=2,
              pad_bottom=2,
              pad_left=2,
              pad_right=2,
              pitch_color='#22312b')

# calculate the maximum grid_height/ width
GRID_WIDTH, GRID_HEIGHT = pitch.calculate_grid_dimensions(figwidth=FIGWIDTH,
                                                          figheight=FIGHEIGHT,
                                                          nrows=NROWS,
                                                          ncols=NCOLS,
                                                          max_grid=MAX_GRID,
                                                          space=0)

# plot using the mplsoccer grid function
fig, ax = pitch.grid(figheight=FIGHEIGHT,
                     grid_width=GRID_WIDTH,
                     grid_height=GRID_HEIGHT,
예제 #12
0
# Filter dataset to only include one teams passes and get boolean mask for the completed passes

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',
              pitch_color='#22312b',
              line_color='#c7d5cc')
fig, ax = pitch.draw(figsize=(16, 11),
                     constrained_layout=True,
                     tight_layout=False)
fig.set_facecolor('#22312b')

# Plot the completed passes
pitch.arrows(df_pass[mask_complete].x,
             df_pass[mask_complete].y,
             df_pass[mask_complete].end_x,
             df_pass[mask_complete].end_y,
             width=2,
             headwidth=10,
             headlength=10,
             color='#ad993c',