### Plot a Radar Chart using mplsoccer Source: https://github.com/andrewrowlinson/mplsoccer/blob/main/README.md Create a radar chart to visualize player attributes using the mplsoccer library. This example shows how to set up the radar, draw circles, plot data values, and add labels. ```python from mplsoccer import Radar import matplotlib.pyplot as plt radar = Radar(params=['Agility', 'Speed', 'Strength'], min_range=[0, 0, 0], max_range=[10, 10, 10]) fig, ax = radar.setup_axis() rings_inner = radar.draw_circles(ax=ax, facecolor='#ffb2b2', edgecolor='#fc5f5f') values = [5, 3, 10] radar_poly, rings, vertices = radar.draw_radar(values, ax=ax, kwargs_radar={'facecolor': '#00f2c1', 'alpha': 0.6}, kwargs_rings={'facecolor': '#d80499', 'alpha': 0.6}) range_labels = radar.draw_range_labels(ax=ax) param_labels = radar.draw_param_labels(ax=ax) plt.show() ``` -------------------------------- ### Install mplsoccer with conda Source: https://github.com/andrewrowlinson/mplsoccer/blob/main/docs/source/index.rst Installs the mplsoccer library using the conda package manager from the conda-forge channel. This is an alternative installation method. ```bash conda install -c conda-forge mplsoccer ``` -------------------------------- ### Pizza Chart with Alternative Values (mplsoccer, Matplotlib) Source: https://context7.com/andrewrowlinson/mplsoccer/llms.txt This example demonstrates creating a pizza chart where the slice sizes are determined by percentile rankings, but the actual raw statistics are displayed alongside. It requires defining both percentile values for visualization and actual values for display. ```python from mplsoccer import PyPizza, FontManager import matplotlib.pyplot as plt # Load fonts font_normal = FontManager('https://raw.githubusercontent.com/googlefonts/roboto/' 'main/src/hinted/Roboto-Regular.ttf') font_bold = FontManager('https://raw.githubusercontent.com/google/fonts/main/' 'apache/robotoslab/RobotoSlab[wght].ttf') # Parameters params = ["Non-Penalty Goals", "npxG", "npxG per Shot", "xA", "Open Play\nShot Creating Actions", "\nPenalty Area\nEntries", "Progressive Passes", "Progressive Carries", "Successful Dribbles"] # Percentile values for slice sizes percentile_values = [99, 99, 87, 51, 62, 58, 45, 40, 27] # Actual raw values to display actual_values = [41, 39.2, 0.31, 7.8, 3.2, 4.1, 2.8, 1.5, 0.9] # The rest of the code to create and display the pizza chart would follow here, # similar to the previous example but using both percentile_values and actual_values. ``` -------------------------------- ### Install mplsoccer with pip Source: https://github.com/andrewrowlinson/mplsoccer/blob/main/docs/source/index.rst Installs the mplsoccer library using the pip package manager. This is the recommended method for most Python users. ```bash pip install mplsoccer ``` -------------------------------- ### Standardize Soccer Coordinates with mplsoccer Source: https://context7.com/andrewrowlinson/mplsoccer/llms.txt Converts football pitch coordinates between different data providers (like StatsBomb) and custom dimensions using mplsoccer's Standardizer. This is crucial for consistent plotting and analysis when working with data from various sources that may use different pitch scales. The example shows transforming StatsBomb coordinates to a custom 105x68 meter pitch. ```python from mplsoccer import Standardizer, Pitch, VerticalPitch, Sbopen import matplotlib.pyplot as plt # Convert StatsBomb to custom pitch dimensions statsbomb_to_custom = Standardizer(pitch_from='statsbomb', pitch_to='custom', length_to=105, width_to=68) # Load StatsBomb data parser = Sbopen() df = parser.event(266653)[0] # Transform coordinates x_std, y_std = statsbomb_to_custom.transform(df.x, df.y) xend_std, yend_std = statsbomb_to_custom.transform(df.end_x, df.end_y) # Update dataframe df['x'] = x_std df['y'] = y_std df['end_x'] = xend_std df['end_y'] = yend_std ``` -------------------------------- ### Load StatsBomb Open Data with mplsoccer Source: https://context7.com/andrewrowlinson/mplsoccer/llms.txt Demonstrates how to load various types of football data from StatsBomb using mplsoccer's Sbopen class. It covers loading competition, match, lineup, event, and tracking data, and shows how to filter specific events like shots and passes from the loaded dataframes. This is essential for any data analysis involving StatsBomb data. ```python from mplsoccer import Sbopen import pandas as pd # Initialize parser parser = Sbopen() # Load competition data df_competition = parser.competition() print(f"Available competitions: {len(df_competition)}") # Load matches for a specific competition/season df_match = parser.match(competition_id=11, season_id=1) print(f"Matches in season: {len(df_match)}") # Load lineup data df_lineup = parser.lineup(7478) print(f"Players in lineups: {len(df_lineup)}") # Load event data (returns 4 dataframes) df_event, df_related, df_freeze, df_tactics = parser.event(7478) print(f"Events: {len(df_event)}, Related: {len(df_related)}") print(f"Freeze frames: {len(df_freeze)}, Tactics: {len(df_tactics)}") # Load 360 tracking data df_frame, df_visible = parser.frame(3788741) print(f"Frames: {len(df_frame)}, Visible players: {len(df_visible)}") # Filter specific events shots = df_event[df_event.type_name == 'Shot'] passes = df_event[df_event.type_name == 'Pass'] team_passes = passes[passes.team_name == 'Barcelona'] print(f"Shots: {len(shots)}, Team passes: {len(team_passes)}") ``` -------------------------------- ### Create and Customize Football Pitch Visualizations Source: https://context7.com/andrewrowlinson/mplsoccer/llms.txt Generates horizontal and vertical football pitches with various styling options. Supports different pitch types and orientations, allowing for customization of colors, stripes, and grid layouts with titles and endnotes. ```python from mplsoccer import Pitch, VerticalPitch import matplotlib.pyplot as plt # Create a horizontal pitch with grass styling pitch = Pitch(pitch_type='statsbomb', pitch_color='grass', line_color='white', stripe=True) fig, ax = pitch.draw(figsize=(10, 7)) # Create a vertical half-pitch for attack visualization vpitch = VerticalPitch(pitch_type='statsbomb', half=True, pitch_color='#22312b', line_color='#efefef') fig, ax = vpitch.draw(figsize=(6, 9)) # Create a pitch grid with title and endnote pitch = Pitch(pitch_type='statsbomb', pitch_color='#1e4259', line_zorder=2) fig, axs = pitch.grid(endnote_height=0.03, title_height=0.08, axis=False, grid_height=0.84) axs['title'].text(0.5, 0.5, "Match Analysis", ha='center', va='center', color='white', fontsize=25) axs['endnote'].text(1, 0.5, '@your_handle', ha='right', va='center', color='white', fontsize=12) plt.show() ``` -------------------------------- ### Formation Plotting with mplsoccer Source: https://context7.com/andrewrowlinson/mplsoccer/llms.txt Creates a vertical football pitch and plots a 4-4-2 formation using player positions. It also adds player numbers to the formation plot, allowing for visualization of team structures. ```python from mplsoccer import VerticalPitch import matplotlib.pyplot as plt # Create vertical pitch pitch = VerticalPitch(pitch_type='statsbomb', half=True, pitch_color='grass', line_color='white') fig, ax = pitch.draw(figsize=(6.875, 10)) # Plot 4-4-2 formation positions = [1, 2, 3, 5, 6, 9, 11, 12, 16, 22, 24] # Player IDs scatter = pitch.formation('442', positions=positions, ax=ax, kind='scatter', c='white', edgecolors='black', s=300, linewidths=2.5, zorder=3) # Add player numbers for i, pos in enumerate(positions): coords = pitch.get_formation('442') ax.text(coords.y.iloc[i], coords.x.iloc[i], str(pos), ha='center', va='center', fontsize=12, color='black', weight='bold', zorder=4) plt.show() ``` -------------------------------- ### Plot a StatsBomb Pitch with mplsoccer Source: https://github.com/andrewrowlinson/mplsoccer/blob/main/docs/source/index.rst Demonstrates how to create a soccer pitch visualization using the mplsoccer library. It initializes a Pitch object with specified colors and lines, then draws the pitch. ```python from mplsoccer import Pitch pitch = Pitch(pitch_color='grass', line_color='white', stripe=True) fig, ax = pitch.draw() ``` -------------------------------- ### KDE Density Plotting with mplsoccer Source: https://context7.com/andrewrowlinson/mplsoccer/llms.txt Creates a Kernel Density Estimation (KDE) plot to visualize player positioning density using mplsoccer. It loads event data, filters for team and event types, draws a pitch, and then generates a KDE plot with a specified colormap and shading. Requires pandas, matplotlib, and mplsoccer. ```python from mplsoccer import Pitch, Sbopen import matplotlib.pyplot as plt # Load and filter data parser = Sbopen() df = parser.event(69249)[0] # Example event ID df_touches = df.loc[(df.team_name == 'Manchester City WFC') & (df.type_name.isin(['Pass', 'Carry', 'Shot'])), ['x', 'y']] # Create pitch pitch = Pitch(pitch_type='statsbomb', line_zorder=2, pitch_color='#22312b', line_color='white') fig, ax = pitch.draw(figsize=(10, 7)) # Plot KDE with custom parameters kde = pitch.kdeplot(df_touches.x, df_touches.y, ax=ax, cmap='hot', shade=True, levels=100, thresh=0.01, alpha=0.7, zorder=1) plt.show() ``` -------------------------------- ### Create Labeled Heatmaps with Custom Spatial Binning Source: https://context7.com/andrewrowlinson/mplsoccer/llms.txt Generates heatmaps with value labels and custom spatial binning. This allows for precise control over how data is aggregated across the pitch and visualized, with normalized statistics and custom bin definitions. ```python from mplsoccer import VerticalPitch, Sbopen import matplotlib.pyplot as plt import numpy as np # Load and filter data parser = Sbopen() df = parser.event(19789)[0] df_pressure = df.loc[(df.team_name == 'Chelsea FCW') & (df.type_name == 'Pressure'), ['x', 'y']] # Create vertical pitch pitch = VerticalPitch(pitch_type='statsbomb', line_zorder=2, pitch_color='#f4edf0') fig, ax = pitch.draw(figsize=(4.125, 6)) # Create custom bins based on pitch dimensions bin_x = np.linspace(pitch.dim.left, pitch.dim.right, num=7) bin_y = np.sort(np.array([pitch.dim.bottom, pitch.dim.six_yard_bottom, pitch.dim.six_yard_top, pitch.dim.top])) # Calculate normalized statistics bin_statistic = pitch.bin_statistic(df_pressure.x, df_pressure.y, statistic='count', bins=(bin_x, bin_y), normalize=True) # Plot with labels pitch.heatmap(bin_statistic, ax=ax, cmap='Reds', edgecolor='#f9f9f9') labels = pitch.label_heatmap(bin_statistic, color='#f4edf0', fontsize=18, ax=ax, ha='center', va='center', str_format='{:.0%}') plt.show() ``` -------------------------------- ### Generate Spatial Density Heatmaps with Gaussian Smoothing Source: https://context7.com/andrewrowlinson/mplsoccer/llms.txt Creates spatial density heatmaps from event data, with options for Gaussian smoothing to reduce noise. This function takes event coordinates, calculates statistics, and plots a heatmap with a colorbar. ```python from mplsoccer import Pitch, Sbopen from scipy.ndimage import gaussian_filter import matplotlib.pyplot as plt # Load StatsBomb data parser = Sbopen() df = parser.event(19789)[0] df_pressure = df.loc[(df.team_name == 'Chelsea FCW') & (df.type_name == 'Pressure'), ['x', 'y']] # Create heatmap with Gaussian smoothing pitch = Pitch(pitch_type='statsbomb', line_zorder=2, pitch_color='#22312b', line_color='#efefef') fig, ax = pitch.draw(figsize=(6.6, 4.125)) # Calculate binned statistics and apply smoothing bin_statistic = pitch.bin_statistic(df_pressure.x, df_pressure.y, statistic='count', bins=(25, 25)) bin_statistic['statistic'] = gaussian_filter(bin_statistic['statistic'], 1) # Plot heatmap with colorbar pcm = pitch.heatmap(bin_statistic, ax=ax, cmap='hot', edgecolors='#22312b') cbar = fig.colorbar(pcm, ax=ax, shrink=0.6) plt.show() ``` -------------------------------- ### Create and Plot Pizza Chart with mplsoccer Source: https://context7.com/andrewrowlinson/mplsoccer/llms.txt Generates a radar chart (pizza chart) using mplsoccer's PyPizza class. It visualizes percentile values against actual values, allowing customization of colors, line widths, and text properties. This is useful for comparing player statistics in a visually intuitive format. ```python from mplsoccer import PyPizza, FontManager import matplotlib.pyplot as plt # Assume params, percentile_values, actual_values, and font_normal are defined elsewhere # Example placeholder definitions: params = { 'Strength': 75, 'Aggression': 60, 'Positioning': 80, 'Stamina': 70, 'Passing': 85, 'Shooting': 90 } percentile_values = [80, 70, 90, 75, 85, 95] actual_values = [85, 72, 92, 78, 88, 98] font_normal = FontManager('path/to/Roboto-Regular.ttf') # Replace with actual font path or URL font_bold = FontManager('path/to/Roboto-Bold.ttf') # Replace with actual font path or URL baker = PyPizza(params=params, straight_line_color="#F2F2F2", straight_line_lw=1, last_circle_lw=0, other_circle_lw=0) fig, ax = baker.make_pizza( percentile_values, figsize=(8, 8), alt_text_values=actual_values, # Display actual values color_blank_space="same", blank_alpha=0.4, kwargs_slices=dict(facecolor="lightcoral", edgecolor="#F2F2F2", zorder=2, linewidth=1), kwargs_params=dict(color="#000000", fontsize=12, fontproperties=font_normal.prop, va="center"), kwargs_values=dict(color="#000000", fontsize=11, fontproperties=font_normal.prop, zorder=3, bbox=dict(edgecolor="#000000", facecolor="lightcoral", boxstyle="round,pad=0.2", lw=1)) ) fig.text(0.515, 0.97, "Robert Lewandowski - FC Bayern Munich", size=18, ha="center", fontproperties=font_bold.prop, color="#000000") fig.text(0.515, 0.942, "Actual Values Displayed | Percentile Rank vs Forwards | 2020-21", size=14, ha="center", fontproperties=font_bold.prop, color="#000000") plt.show() ``` -------------------------------- ### Load and Plot Passes with Scatter using mplsoccer Source: https://context7.com/andrewrowlinson/mplsoccer/llms.txt Loads pass data using Sbopen, filters for specific teams and pass events, calculates pass angles, and visualizes passes as scatter points with rotation based on angle using mplsoccer. ```python from mplsoccer import Pitch, Sbopen import matplotlib.pyplot as plt import numpy as np # Load pass data parser = Sbopen() df = parser.event(69249)[0] df_pass = df.loc[(df.type_name == 'Pass') & (df.team_name == 'Manchester City WFC'), ['x', 'y', 'end_x', 'end_y']] # Calculate pass angles df_pass['angle'] = np.degrees( np.arctan2(df_pass.end_y - df_pass.y, df_pass.end_x - df_pass.x) ) # Create pitch and plot pitch = Pitch(pitch_type='statsbomb', pitch_color='grass', line_color='white', stripe=True) fig, ax = pitch.draw(figsize=(12, 8)) # Scatter with rotation pitch.scatter(df_pass.x, df_pass.y, rotation_degrees=df_pass.angle, marker='>', s=150, c='blue', edgecolors='black', linewidth=1, ax=ax) plt.show() ``` -------------------------------- ### Plot Events with Custom Markers and Rotation Source: https://context7.com/andrewrowlinson/mplsoccer/llms.txt Illustrates how to plot events on a football pitch using custom markers and rotation. This functionality is useful for visualizing the direction or orientation of specific actions within a match. ```python from mplsoccer import Pitch, Sbopen import matplotlib.pyplot as plt import numpy as np ``` -------------------------------- ### Create Pizza Chart for Player Statistics (mplsoccer, Matplotlib) Source: https://context7.com/andrewrowlinson/mplsoccer/llms.txt This code generates a pizza chart to visualize player percentile rankings using mplsoccer. It involves loading custom fonts, defining parameters and their corresponding percentile values, and styling the chart with various options for slices, parameters, and values. ```python from mplsoccer import PyPizza, FontManager import matplotlib.pyplot as plt # Load fonts font_normal = FontManager('https://raw.githubusercontent.com/googlefonts/roboto/' 'main/src/hinted/Roboto-Regular.ttf') font_bold = FontManager('https://raw.githubusercontent.com/google/fonts/main/' 'apache/robotoslab/RobotoSlab[wght].ttf') # Define parameters and percentile values params = ["Non-Penalty Goals", "npxG", "npxG per Shot", "xA", "Open Play\nShot Creating Actions", "\nPenalty Area\nEntries", "Progressive Passes", "Progressive Carries", "Successful Dribbles", "\nTouches\nper Turnover", "pAdj\nPress Regains", "Aerials Won"] values = [99, 99, 87, 51, 62, 58, 45, 40, 27, 74, 77, 73] # Create pizza chart baker = PyPizza(params=params, straight_line_color="#000000", straight_line_lw=1, last_circle_lw=1, other_circle_lw=1, other_circle_ls="-.") # Plot with styling fig, ax = baker.make_pizza( values, figsize=(8, 8), param_location=110, color_blank_space="same", blank_alpha=0.4, kwargs_slices=dict(facecolor="cornflowerblue", edgecolor="#F2F2F2", zorder=2, linewidth=1), kwargs_params=dict(color="#000000", fontsize=12, fontproperties=font_normal.prop, va="center"), kwargs_values=dict(color="#000000", fontsize=12, fontproperties=font_normal.prop, zorder=3, bbox=dict(edgecolor="#000000", facecolor="cornflowerblue", boxstyle="round,pad=0.2", lw=1)) ) # Add title and credits fig.text(0.515, 0.97, "Robert Lewandowski - FC Bayern Munich", size=18, ha="center", fontproperties=font_bold.prop, color="#000000") fig.text(0.515, 0.942, "Percentile Rank vs Top-Five League Forwards | Season 2020-21", size=15, ha="center", fontproperties=font_bold.prop, color="#000000") plt.show() ``` -------------------------------- ### Hexbin Density Plotting with mplsoccer Source: https://context7.com/andrewrowlinson/mplsoccer/llms.txt Generates a hexagonal binning density plot for player positioning data using mplsoccer. It loads event data, filters for a specific player, draws a pitch, and then plots the player's positions as hexbins with a specified colormap and grid size. Requires pandas, matplotlib, and mplsoccer. ```python from mplsoccer import VerticalPitch, Sbopen import matplotlib.pyplot as plt # Load data for specific player parser = Sbopen() df = parser.event(69249)[0] # Example event ID df_player = df.loc[df.player_id == 5503, ['x', 'y']] # Create vertical pitch pitch = VerticalPitch(pitch_type='statsbomb', line_color='#000009', line_zorder=2, pitch_color='white') fig, ax = pitch.draw(figsize=(4.4, 6.4)) # Plot hexbin with colormap hexmap = pitch.hexbin(df_player.x, df_player.y, ax=ax, edgecolors='#f4f4f4', gridsize=(8, 8), cmap='Reds', mincnt=1, alpha=0.8) # Add colorbar cbar = plt.colorbar(hexmap, ax=ax, orientation='horizontal', pad=0.05, aspect=40) cbar.set_label('Touch count', fontsize=12) plt.show() ``` -------------------------------- ### Coordinate Transformation with mplsoccer Standardizer Source: https://context7.com/andrewrowlinson/mplsoccer/llms.txt Demonstrates reversing coordinate transformations using the Standardizer class from mplsoccer. This is useful for converting standardized coordinates back to their original format. It takes standardized x and y values and returns original coordinates. ```python from mplsoccer import Standardizer # Assuming 'statsbomb_to_custom' is an initialized Standardizer object # and 'x_std', 'y_std' are standardized coordinates x_original, y_original = statsbomb_to_custom.transform( x_std, y_std, reverse=True ) ``` -------------------------------- ### Add Labels and Scatter Points to Radar Chart (Matplotlib) Source: https://context7.com/andrewrowlinson/mplsoccer/llms.txt This snippet demonstrates how to add range and parameter labels to a radar chart using mplsoccer's radar object. It also shows how to plot player vertices as scatter points on the chart, customizing their appearance. ```python from mplsoccer import RadarAxes, FontManager import matplotlib.pyplot as plt # Assume ax, vertices1, vertices2, radar, robotto_thin are defined previously # Example placeholder definitions: fig, axs = plt.subplots(ncols=2, figsize=(12, 6)) radar_chart = RadarAxes(ax=axs['radar'], params=["Stat 1", "Stat 2", "Stat 3"], grid_label_fontproperties=robotto_thin.prop) vertices1 = [[1, 2, 3]] vertices2 = [[2, 3, 1]] # Add labels range_labels = radar.draw_range_labels(ax=axs['radar'], fontsize=20, fontproperties=robotto_thin.prop) param_labels = radar.draw_param_labels(ax=axs['radar'], fontsize=20, fontproperties=robotto_thin.prop) # Add vertices as scatter points axs['radar'].scatter(vertices1[:, 0], vertices1[:, 1], c='#00f2c1', edgecolors='#6d6c6d', marker='o', s=150, zorder=2) axs['radar'].scatter(vertices2[:, 0], vertices2[:, 1], c='#d80499', edgecolors='#6d6c6d', marker='o', s=150, zorder=2) # Add titles axs['title'].text(0.01, 0.65, 'Bruno Fernandes', fontsize=25, color='#01c49d', ha='left', va='center', weight='bold') axs['title'].text(0.99, 0.65, 'Kevin De Bruyne', fontsize=25, color='#d80499', ha='right', va='center', weight='bold') plt.show() ``` -------------------------------- ### Create and Plot Bumpy Chart for Rankings with mplsoccer Source: https://context7.com/andrewrowlinson/mplsoccer/llms.txt Visualizes team ranking changes over a season using mplsoccer's Bumpy class. It takes weekly match data and team rankings as input, highlighting specified teams with distinct colors. This chart is ideal for tracking team performance trends over time. ```python from mplsoccer import Bumpy, FontManager import matplotlib.pyplot as plt import numpy as np # Load fonts font_normal = FontManager('https://raw.githubusercontent.com/googlefonts/roboto/' 'main/src/hinted/Roboto-Regular.ttf') # Weekly match data match_day = ["Week " + str(num) for num in range(1, 39)] # Team rankings per week (sample data structure) season_dict = { "Liverpool": [1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], "Man City": [2, 3, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2], "Man Utd": [15, 14, 13, 12, 10, 9, 7, 6, 5, 5, 5, 5, 5, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 3, 3, 3, 3, 3, 3, 3, 3, 3] } # Teams to highlight highlight_dict = {"Liverpool": "crimson", "Man City": "skyblue", "Man Utd": "gold"} # Create bumpy chart bumpy = Bumpy(scatter_color="#282A2C", line_color="#252525", rotate_xticks=90, ticklabel_size=17, label_size=30, scatter_primary='D', show_right=True, plot_labels=True, alignment_yvalue=0.1, alignment_xvalue=0.065) fig, ax = bumpy.plot( x_list=match_day, y_list=np.linspace(1, 20, 20).astype(int), values=season_dict, secondary_alpha=0.5, highlight_dict=highlight_dict, figsize=(20, 16), x_label='Week', y_label='Position', ylim=(-0.1, 23), lw=2.5, fontproperties=font_normal.prop ) # Add title fig.text(0.09, 0.95, "Premier League 2019/20 week-wise standings:", size=29, color="#F2F2F2", weight='bold') plt.tight_layout(pad=0.5) plt.show() ``` -------------------------------- ### Arrow Plotting for Pass Networks with mplsoccer Source: https://context7.com/andrewrowlinson/mplsoccer/llms.txt Loads pass data, filters passes based on cell location using bin statistics, and visualizes the filtered passes as arrows and scatter points on a football pitch using mplsoccer. This allows for analysis of pass flow between specific areas of the pitch. ```python from mplsoccer import Pitch, Sbopen import matplotlib.pyplot as plt import numpy as np # Load pass data parser = Sbopen() df = parser.event(19789)[0] df_pass = df.loc[(df.team_name == 'Chelsea FCW') & (df.type_name == 'Pass'), ['x', 'y', 'end_x', 'end_y']] # Create pitch pitch = Pitch(line_zorder=2) fig, ax = pitch.draw(figsize=(12, 8)) # Get bin numbers for start and end positions bin_statistic = pitch.bin_statistic(df_pass.x, df_pass.y, bins=(6, 5)) bin_statistic_end = pitch.bin_statistic(df_pass.end_x, df_pass.end_y, bins=(6, 5)) # Filter passes from one cell to another (e.g., 5th box to 6th box) mask_start = np.logical_and(bin_statistic['binnumber'][0] == 4, bin_statistic['binnumber'][1] == 1) mask_end = np.logical_and(bin_statistic_end['binnumber'][0] == 5, bin_statistic_end['binnumber'][1] == 2) mask = np.logical_and(mask_start, mask_end) # Plot filtered passes as arrows pitch.arrows(df_pass.x[mask], df_pass.y[mask], df_pass.end_x[mask], df_pass.end_y[mask], ax=ax, zorder=10, color='midnightblue', width=2) pitch.scatter(df_pass.x[mask], df_pass.y[mask], ax=ax, fc='hotpink', marker='o', s=100, ec='darkslategrey', lw=3, alpha=0.6) plt.show() ``` -------------------------------- ### Convert Wyscout to StatsBomb Coordinates with mplsoccer Source: https://context7.com/andrewrowlinson/mplsoccer/llms.txt Converts football pitch coordinates from Wyscout format to StatsBomb format using the Standardizer class. This process maintains the relative position of elements to pitch markings like penalty boxes and center lines. It's essential for data from different providers. ```python from mplsoccer import Standardizer # Initialize the standardizer for Wyscout to StatsBomb conversion wyscout_to_sb = Standardizer(pitch_from='wyscout', pitch_to='statsbomb') # To use this, you would then apply its transform method to your Wyscout data: # x_statsbomb, y_statsbomb = wyscout_to_sb.transform(x_wyscout, y_wyscout) ``` -------------------------------- ### Radar Chart for Player Comparison using mplsoccer Source: https://context7.com/andrewrowlinson/mplsoccer/llms.txt Generates radar charts to compare player statistics. It loads a custom font, defines parameters and ranges, sets player values, and draws the radar chart with comparison lines using mplsoccer's Radar and grid functionalities. ```python from mplsoccer import Radar, FontManager, grid import matplotlib.pyplot as plt # Load custom font URL = 'https://raw.githubusercontent.com/googlefonts/roboto/main/src/hinted/Roboto-Thin.ttf' robotto_thin = FontManager(URL) # Define parameters and ranges params = ["npxG", "Non-Penalty Goals", "xA", "Key Passes", "Through Balls", "Progressive Passes", "Shot-Creating Actions", "Dribbles Completed"] low = [0.08, 0.0, 0.1, 1, 0.6, 4, 3, 0.3] high = [0.37, 0.6, 0.6, 4, 1.2, 10, 8, 1.5] # Player values (percentiles) bruno_values = [0.22, 0.25, 0.30, 2.54, 0.43, 5.60, 4.34, 0.69] Bruyne_values = [0.25, 0.52, 0.37, 3.59, 0.41, 6.36, 5.68, 1.23] # Create radar radar = Radar(params, low, high, num_rings=4, ring_width=1, center_circle_radius=1) # Setup figure with title/endnote fig, axs = grid(figheight=14, grid_height=0.915, title_height=0.06, endnote_height=0.025, title_space=0, endnote_space=0, grid_key='radar', axis=False) # Draw radar comparison radar.setup_axis(ax=axs['radar']) rings_inner = radar.draw_circles(ax=axs['radar'], facecolor='#ffb2b2', edgecolor='#fc5f5f') radar_output = radar.draw_radar_compare(bruno_values, Bruyne_values, ax=axs['radar'], kwargs_radar={'facecolor': '#00f2c1', 'alpha': 0.6}, kwargs_compare={'facecolor': '#d80499', 'alpha': 0.6}) radar_poly, radar_poly2, vertices1, vertices2 = radar_output ``` -------------------------------- ### Calculate Distances on Custom Pitch with mplsoccer Source: https://context7.com/andrewrowlinson/mplsoccer/llms.txt Calculates the angle and distance of passes on a custom-defined football pitch. It uses the VerticalPitch class from mplsoccer to define pitch dimensions and then computes these metrics from pass data. Requires pandas DataFrames with x, y, end_x, and end_y coordinates. ```python from mplsoccer import VerticalPitch # Assuming 'df' is a pandas DataFrame with 'type_name', 'x', 'y', 'end_x', 'end_y' columns df_pass = df[df.type_name == 'Pass'].copy() custom_pitch = VerticalPitch(pitch_type='custom', pitch_length=105, pitch_width=68) angle, distance = custom_pitch.calculate_angle_and_distance( df_pass.x, df_pass.y, df_pass.end_x, df_pass.end_y ) print(f"Average pass distance: {distance.mean():.2f} meters") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.