### Install sportypy Package using pip Source: https://github.com/sportsdataverse/sportypy/blob/main/docs/_build/html/_sources/index.md.txt This code snippet demonstrates how to install the sportypy package using pip, the standard package installer for Python. Ensure you have Python and pip installed on your system before running this command. ```bash pip install sportypy ``` -------------------------------- ### Create and Draw an NHL Rink using sportypy Source: https://github.com/sportsdataverse/sportypy/blob/main/docs/_build/html/_sources/index.md.txt This example shows how to import the NHLRink class from the sportypy.surfaces.hockey submodule, instantiate an NHL rink object, and then draw the rink. The `draw()` method visualizes the playing surface. ```python # Load from the hockey submodule in surfaces from sportypy.surfaces.hockey import NHLRink # Create the NHL rink nhl = NHLRink() # Draw the NHL rink nhl.draw() ``` -------------------------------- ### Run Code Coverage Tests with Pytest Source: https://github.com/sportsdataverse/sportypy/blob/main/CONTRIBUTING.md This command uses pytest to check code coverage for the sportypy package. It requires the pytest package to be installed and will output the coverage report to the terminal. Ensure your new code maintains 100% coverage. ```bash pip install pytest pytest --cov=sportypy tests/ --cov-config=.coveragerc --cov-report=term ``` -------------------------------- ### Draw NBA Court - sportypy Source: https://github.com/sportsdataverse/sportypy/blob/main/docs/index.md This example shows how to draw a standard NBA basketball court using the `NBACourt` class from the `sportypy.surfaces.basketball` module. The `draw` method is called without any arguments to render the default court. ```python from sportypy.surfaces.basketball import NBACourt NBACourt().draw() ``` -------------------------------- ### Initialize NFL Field for Red Zone Analysis in Python Source: https://github.com/sportsdataverse/sportypy/blob/main/docs/index.md This example illustrates importing the NFLField class from the football submodule. It's a precursor to potentially using the 'display_range' parameter to focus on specific areas like the 'red zone'. ```python # Import football fields from sportypy.surfaces.football import NFLField ``` -------------------------------- ### NHL Rink Visualization with Contour, Heatmap, and Hexbin Plots (Python) Source: https://github.com/sportsdataverse/sportypy/blob/main/docs/_build/html/index.html This example demonstrates creating advanced visualizations on an NHL rink using sportypy. It generates three plots side-by-side: a contour plot showing goal probability, a heatmap of shot locations, and a hexbin plot. The code processes play-by-play data, normalizes coordinates, and utilizes the NHLRink object for drawing and plotting. ```python import pandas as pd import numpy as np from matplotlib import pyplot as plt from sportypy.surfaces.hockey import NHLRink # Download the data pbp = pd.read_csv( "https://hockey-data.harryshomer.com/pbp/nhl_pbp20192020.csv.gz", compression = "gzip" ) # Find all shots pbp["goal"] = (pbp["Event"] == "GOAL").astype(int) # Force all x coordinates to be on the same side of the ice pbp["x"] = np.abs(pbp["xC"]) # Adjust the y coordinates so the shots are from the same direction pbp["y"] = pbp["yC"] * np.sign(pbp["xC"]) # Subset to only shots pbp = pbp.loc[ (pbp.Ev_Zone == "Off") & ~pbp["x"].isna() & ~pbp["y"].isna() & (pbp.Event.isin(["GOAL", "SHOT", "MISS"])) ] # Select only relevant columns to reduce data load time pbp = pbp[["x", "y", "goal"]] # Create a matplotlib.Axes object for the test plots to lie on fig, axs = plt.subplots(1, 3, figsize = (14, 8)) # Instantiate an NHL rink nhl = NHLRink() # Draw a rink on each of the three matplotlib.Axes objects defined above # and subset them to only the offensive zone for i in range(3): nhl.draw(ax = axs[i], display_range = "ozone") # Add the contour plot contour_img = nhl.contourf( pbp["x"], pbp["y"], values = pbp["goal"], ax = axs[0], cmap = "bwr", plot_range = "ozone", binsize = 10, levels = 50, statistic = "mean" ) # Add a colorbar legend to the bottom to make the metrics easier to read plt.colorbar(contour_img, ax = axs[0], orientation = "horizontal") # Add the heatmap plot nhl.heatmap( pbp["x"], pbp["y"], values = pbp["goal"], ax = axs[1], cmap = "magma", plot_xlim = (25, 89), # offensive-side blue line to the goal line statistic = "mean", vmax = 0.2, binsize = 3 ) # Add the hexbin plot nhl.hexbin( pbp["x"], pbp["y"], values = pbp["goal"], ax = axs[2], binsize = (8, 12), plot_range = "ozone", zorder = 25, alpha = 0.85 ) plt.show() ``` -------------------------------- ### Visualize Hockey Passes with Arrow Plot on PHF Rink Source: https://github.com/sportsdataverse/sportypy/blob/main/docs/_build/html/_sources/index.md.txt This example demonstrates how to plot hockey passes using an arrow plot on a PHF rink. It utilizes the same data as the shot plotting example and filters for 'Play' events. The PHFRink object is used to draw the rink, and a scatter plot with arrows indicates the start and end points of passes. ```python # Show passing start/end locations with an arrow plot # This relies on the same Big Data Cup dataset cleaned above # Filter to only be Boston's passes passes = bdc.loc[ (bdc["Team"] == "Boston Pride") & (bdc["Event"] == "Play") ] # Instantiate a PHF rink, adjusting the coordinates to match the data # (The coordinate (0, 0) is in the bottom-left of the plot) phf = PHFRink(x_trans = 100.0, y_trans = 42.5) # Draw the rink on a matplotlib.Axes object fig, ax = plt.subplots(1, 1) phf.draw(ax = ax) # Add the arrow plot of Boston's passes phf.arrow( passes["X Coordinate"], passes["Y Coordinate"], passes["X Coordinate 2"], passes["Y Coordinate 2"], color = "#ffcb05" ) ``` -------------------------------- ### Generate Hockey Shot Density Hexbin Plot using Python Source: https://context7.com/sportsdataverse/sportypy/llms.txt Creates a hexagonal binning visualization to represent shot density on an NHL rink. This involves loading and processing play-by-play data similar to the heatmap example, then utilizing the NHLRink's hexbin function for aggregation and visualization. ```python import pandas as pd import numpy as np import matplotlib.pyplot as plt from sportypy.surfaces.hockey import NHLRink # Load NHL play-by-play data pbp = pd.read_csv( "https://hockey-data.harryshomer.com/pbp/nhl_pbp20192020.csv.gz", compression="gzip" ) # Process data pbp["goal"] = (pbp["Event"] == "GOAL").astype(int) pbp["x"] = np.abs(pbp["xC"]) pbp["y"] = pbp["yC"] * np.sign(pbp["xC"]) pbp = pbp.loc[ (pbp.Ev_Zone == "Off") & ~pbp["x"].isna() & ~pbp["y"].isna() & (pbp.Event.isin(["GOAL", "SHOT", "MISS"])) ][["x", "y", "goal"]] # Create hexbin plot nhl = NHLRink() fig, ax = plt.subplots(1, 1, figsize=(10, 8)) nhl.draw(ax=ax, display_range="ozone") nhl.hexbin( pbp["x"], pbp["y"], values=pbp["goal"], ax=ax, binsize=(8, 12), plot_range="ozone", cmap="YlOrRd", zorder=25, alpha=0.85 ) plt.title("NHL Shot Density - Hexbin Visualization") plt.show() ``` -------------------------------- ### Custom NCAA Court Colors Source: https://context7.com/sportsdataverse/sportypy/llms.txt Customize the appearance of a basketball court using a dictionary of color definitions. This example creates an NCAA court with custom colors simulating the University of Illinois' team colors. It requires matplotlib for display and accepts a `colors_dict` argument for detailed color customization. ```python from sportypy.surfaces.basketball import NCAACourt import matplotlib.pyplot as plt # Create custom NCAA court with University of Illinois colors illini_court = NCAACourt( colors_dict={ "offensive_half_court": "#e8e0d7", "defensive_half_court": "#e8e0d7", "court_apron": "#e84a27", "two_point_range": ["#e8e0d7", "#ffffff66"], "center_circle_fill": "#e8e0d7", "painted_area": ["#e84a27", None], "free_throw_circle_fill": "#e8e0d7", "sideline": "#13294b", "endline": "#13294b", "division_line": "#13294b", "center_circle_outline": "#13294b", "lane_boundary": ["#ffffff", "#ffffff00"], "three_point_line": ["#13294b", "#ffffff"], "free_throw_circle_outline": "#ffffff", "lane_space_mark": "#ffffff", "restricted_arc": "#13294b", "backboard": "#13294b" } ) fig, ax = plt.subplots(1, 1, figsize=(12, 8)) illini_court.draw(ax=ax) plt.title("Custom Illinois Fighting Illini Basketball Court") plt.show() ``` -------------------------------- ### Generate Hockey Probability Surface Contour Plot using Python Source: https://context7.com/sportsdataverse/sportypy/llms.txt Demonstrates creating contour plots to visualize continuous probability or density surfaces for hockey events. This example processes NHL play-by-play data to derive shot and goal information, standardizes coordinates, and prepares data for contour plotting on an NHL rink. ```python import pandas as pd import numpy as np import matplotlib.pyplot as plt from sportypy.surfaces.hockey import NHLRink # Load NHL play-by-play data pbp = pd.read_csv( "https://hockey-data.harryshomer.com/pbp/nhl_pbp20192020.csv.gz", compression="gzip" ) # Process data pbp["goal"] = (pbp["Event"] == "GOAL").astype(int) pbp["x"] = np.abs(pbp["xC"]) pbp["y"] = pbp["yC"] * np.sign(pbp["xC"]) pbp = pbp.loc[ (pbp.Ev_Zone == "Off") & ~pbp["x"].isna() & ~pbp["y"].isna() & (pbp.Event.isin(["GOAL", "SHOT", "MISS"])) ][["x", "y", "goal"]] ``` -------------------------------- ### Coordinate Transformation for PHF Rink Source: https://context7.com/sportsdataverse/sportypy/llms.txt Shift and rotate sport surfaces to align with custom data coordinate systems. This example demonstrates transforming a PHF rink where the origin (0,0) is at the bottom-left instead of the center. It requires matplotlib for visualization and accepts parameters for translation (x_trans, y_trans) and rotation. ```python from sportypy.surfaces.hockey import PHFRink import matplotlib.pyplot as plt # Create a PHF rink with coordinate transformation # Data has (0, 0) at bottom-left instead of center phf = PHFRink( x_trans=100.0, # Shift x-axis by 100 units y_trans=42.5, # Shift y-axis by 42.5 units rotation=90 # Rotate 90 degrees counterclockwise ) fig, ax = plt.subplots(1, 1, figsize=(10, 8)) phf.draw(ax=ax) plt.title("PHF Rink with Coordinate Transformation") plt.show() ``` -------------------------------- ### Draw Curling House using sportypy Source: https://github.com/sportsdataverse/sportypy/blob/main/docs/_build/html/_sources/index.md.txt This example shows how to draw only the 'house' area of a curling sheet using the WCFSheet class from the sportypy.surfaces.curling module. This is useful for focusing on specific areas of play and requires specifying the display_range as 'house'. ```python # Import the curling sheets from sportypy.surfaces.curling import WCFSheet # Draw only the house of a curling sheet WCFSheet().draw(display_range = "house") ``` -------------------------------- ### Process NHL Play-by-Play Data for Shot Analysis Source: https://github.com/sportsdataverse/sportypy/blob/main/README.md This example processes NHL play-by-play data to prepare it for shot analysis. It downloads data, calculates 'goal' events, normalizes 'x' and 'y' coordinates to ensure consistency, and filters for relevant shot events (GOAL, SHOT, MISS). The processed data, containing 'x', 'y', and 'goal' columns, can then be used for plotting on an NHL rink. ```python # This example adapted from the hockey_rink package's documentation, but can be # found here: https://github.com/the-bucketless/hockey_rink#examples # Import packages import pandas as pd from sportypy.surfaces.hockey import NHLRink # Download the data pbp = pd.read_csv( "https://hockey-data.harryshomer.com/pbp/nhl_pbp20192020.csv.gz", compression = "gzip" ) # Find all shots pbp["goal"] = (pbp["Event"] == "GOAL").astype(int) # Force all x coordinates to be on the same side of the ice pbp["x"] = np.abs(pbp["xC"]) # Adjust the y coordinates so the shots are from the same direction pbp["y"] = pbp["yC"] * np.sign(pbp["xC"]) # Subset to only shots pbp = pbp.loc[ (pbp.Ev_Zone == "Off") & \ ~pbp["x"].isna() & \ ~pbp["y"].isna() & (pbp.Event.isin(["GOAL", "SHOT", "MISS"])) ] # Select only relevant columns to reduce data load time pbp = pbp[["x", "y", "goal"]] ``` -------------------------------- ### Check Court Dimensions That Can Be Changed Source: https://github.com/sportsdataverse/sportypy/blob/main/docs/_build/html/surfaces/basketball.html This function helps identify which features of a basketball court can be re-parameterized. It's useful for users customizing court dimensions or using existing league dimensions as a starting point. The function prints the names of re-parameterizable features. ```python from sportypy.surfaces.basketball import BasketballCourt court = BasketballCourt() court.cani_change_dimensions() ``` -------------------------------- ### Scatter Plot for Event Locations (Hockey) Source: https://context7.com/sportsdataverse/sportypy/llms.txt Plot discrete events, such as shots or player positions, onto a playing surface using a pandas DataFrame. This example loads hockey data from a CSV file and filters it for a specific game to prepare for plotting. Requires pandas and matplotlib. ```python import pandas as pd import matplotlib.pyplot as plt from sportypy.surfaces.hockey import PHFRink # Load Big Data Cup hockey data bdc = pd.read_csv( "https://raw.githubusercontent.com/bigdatacup/Big-Data-Cup-2021/main/hackathon_nwhl.csv" ) # Filter to specific game bdc = bdc.loc[ (bdc["Home Team"] == "Minnesota Whitecaps") & (bdc["Away Team"] == "Boston Pride") ] ``` -------------------------------- ### Visualize Passes with Arrow Plot on PHF Rink Source: https://github.com/sportsdataverse/sportypy/blob/main/README.md This code snippet visualizes hockey passes as arrows on a PHF rink. It uses the same Big Data Cup dataset, filtering for 'Play' events and Boston's passes. A PHFRink object is instantiated and drawn, followed by an arrow plot to show the start and end points of each pass. This helps in analyzing team passing patterns. ```python # Show passing start/end locations with an arrow plot # This relies on the same Big Data Cup dataset cleaned above # Filter to only be Boston's passes passes = bdc.loc[ (bdc["Team"] == "Boston Pride") & \ (bdc["Event"] == "Play") ] # Instantiate a PHF rink, adjusting the coordinates to match the data # (The coordinate (0, 0) is in the bottom-left of the plot) phf = PHFRink(x_trans = 100.0, y_trans = 42.5) # Draw the rink on a matplotlib.Axes object fig, ax = plt.subplots(1, 1) phf.draw(ax = ax) # Add the arrow plot of Boston's passes phf.arrow( passes["X Coordinate"], passes["Y Coordinate"], passes["X Coordinate 2"], passes["Y Coordinate 2"], color = "#ffcb05" ) ``` -------------------------------- ### Plot Hockey Passes on PHF Rink (Python) Source: https://github.com/sportsdataverse/sportypy/blob/main/docs/_build/html/index.html This code snippet visualizes hockey passes as arrows on a PHF rink. It uses the same Big Data Cup dataset, filters for passes made by the Boston Pride, and then uses the PHFRink object to draw the rink and an arrow plot to represent the start and end points of each pass. The coordinate system is adjusted for the rink's orientation. ```python import pandas as pd from matplotlib import pyplot as plt from sportypy.surfaces.hockey import PHFRink # Download the data (assuming bdc is already loaded from previous step) # If not, uncomment the following lines: # bdc = pd.read_csv( # "https://raw.githubusercontent.com/bigdatacup/Big-Data-Cup-2021/" # "main/hackathon_nwhl.csv" # ) # Filter to only be Boston's passes passes = bdc.loc[ (bdc["Team"] == "Boston Pride") & (bdc["Event"] == "Play") ] # Instantiate a PHF rink, adjusting the coordinates to match the data # (The coordinate (0, 0) is in the bottom-left of the plot) phf = PHFRink(x_trans = 100.0, y_trans = 42.5) # Draw the rink on a matplotlib.Axes object fig, ax = plt.subplots(1, 1) phf.draw(ax = ax) # Add the arrow plot of Boston's passes phf.arrow( passes["X Coordinate"], passes["Y Coordinate"], passes["X Coordinate 2"], passes["Y Coordinate 2"], color = "#ffcb05" ) plt.show() ``` -------------------------------- ### NHL Rink and NBA Court Unit Conversion Source: https://context7.com/sportsdataverse/sportypy/llms.txt Demonstrates how to work with sports data in different units by specifying surface unit parameters in SportyPy. It shows how to create NHL and NBA courts/rinks with dimensions set to meters instead of the default feet, using NHLRink and NBACourt classes. ```python from sportypy.surfaces.hockey import NHLRink import matplotlib.pyplot as plt # NHL rule book uses feet, but data might be in meters # Create rink with unit conversion nhl_meters = NHLRink( rink_updates={ "rink_units": "m" # Convert all dimensions to meters } ) fig, ax = plt.subplots(1, 1, figsize=(12, 8)) nhl_meters.draw(ax=ax) plt.title("NHL Rink in Meters (Instead of Feet)") plt.show() # You can also specify units when instantiating from sportypy.surfaces.basketball import NBACourt # NBA court in meters instead of feet nba_meters = NBACourt( court_updates={ "court_units": "m" } ) fig, ax = plt.subplots(1, 1, figsize=(12, 8)) nba_meters.draw(ax=ax) plt.title("NBA Court in Meters") plt.show() ``` -------------------------------- ### SportyPy Baseball Field Catcher's Box Shape Source: https://github.com/sportsdataverse/sportypy/blob/main/docs/_build/html/surfaces/baseball.html This parameter defines the shape of the catcher's box. Currently, 'rectangle' is the default behavior, and 'trapezoid' is supported, as seen in the LittleLeagueField example. This influences how the catcher's area is rendered or calculated. ```text catchers_box_shape: str (supported values: 'rectangle', 'trapezoid') ``` -------------------------------- ### Create NBA Shot Heatmap with Sportypy and NBA API Source: https://github.com/sportsdataverse/sportypy/blob/main/docs/_build/html/_sources/index.md.txt Generates an NBA shot heatmap using player shot data from the NBA API and visualized with sportypy. The code retrieves shot data, processes coordinates, and plots a heatmap of shot results on a basketball court. ```python import json import numpy as np import pandas as pd import math # Import math for trigonometric functions import matplotlib.pyplot as plt from sportypy.surfaces.basketball import NBACourt from nba_api.stats.endpoints import shotchartdetail # Make API request for player shot data response = shotchartdetail.ShotChartDetail( team_id = 0, player_id = 1630245, # Example: Ayo Dosunmu season_nullable = "2021-22", season_type_all_star = "Regular Season", context_measure_simple = "FGA" ) # Extract the json content content = json.loads(response.get_json()) # Form the data set results = content["resultSets"][0] headers = results["headers"] rows = results["rowSet"] shot_data = pd.DataFrame(rows) shot_data.columns = headers # Rotate the coordinates to align with sportypy convention theta = 0.5 * np.pi shot_data["x_r"] = ( (shot_data["LOC_X"] * math.cos(theta)) - (shot_data["LOC_Y"] * math.sin(theta)) ) shot_data["y_r"] = ( (shot_data["LOC_X"] * math.sin(theta)) + (shot_data["LOC_Y"] * math.cos(theta)) ) # Divide by 10 since NBA API gives coordinates in 1/10 of feet measurements shot_data["LOC_X"] = shot_data["x_r"] / 10.0 shot_data["LOC_Y"] = shot_data["y_r"] / 10.0 # Drop extra columns shot_data.drop(labels = ["x_r", "y_r"], axis = 1, inplace=True) # Create SHOT_RESULT used for heatmapping shot_data["SHOT_RESULT"] = np.where( shot_data["EVENT_TYPE"] == "Made Shot", 1, 0 ) # Define the matplotlib instances to plot onto fig, ax = plt.subplots(1, 1) # Instantiate a court class and draw the court nba = NBACourt(x_trans = -41.75) ax = nba.draw(display_range = "offense") # Add the heatmap nba.heatmap( shot_data["LOC_X"], shot_data["LOC_Y"], values = shot_data["SHOT_RESULT"], ax = ax, alpha = 0.75, cmap = "hot" ) ``` -------------------------------- ### Create NBA Shot Chart with Unit Conversion Source: https://context7.com/sportsdataverse/sportypy/llms.txt Generates an NBA shot chart with coordinate rotation and unit conversion for NBA API data. It fetches shot data using nba_api, rotates and converts coordinates, and then visualizes the shot distribution using NBACourt from sportypy.surfaces.basketball. The function requires player ID, team ID, and season as input. ```python import json import math import numpy as np import pandas as pd import matplotlib.pyplot as plt from sportypy.surfaces.basketball import NBACourt from nba_api.stats.endpoints import shotchartdetail # Fetch NBA shot data (Ayo Dosunmu's rookie season) response = shotchartdetail.ShotChartDetail( team_id=0, player_id=1630245, season_nullable="2021-22", season_type_all_star="Regular Season", context_measure_simple="FGA" ) # Parse JSON response content = json.loads(response.get_json()) results = content["resultSets"][0] shot_data = pd.DataFrame(results["rowSet"]) shot_data.columns = results["headers"] # Rotate coordinates to match sportypy convention theta = 0.5 * np.pi shot_data["x_r"] = ( (shot_data["LOC_X"] * math.cos(theta)) - (shot_data["LOC_Y"] * math.sin(theta)) ) shot_data["y_r"] = ( (shot_data["LOC_X"] * math.sin(theta)) + (shot_data["LOC_Y"] * math.cos(theta)) ) # Convert from 1/10 feet to feet shot_data["LOC_X"] = shot_data["x_r"] / 10.0 shot_data["LOC_Y"] = shot_data["y_r"] / 10.0 # Create shot result indicator shot_data["SHOT_RESULT"] = np.where( shot_data["EVENT_TYPE"] == "Made Shot", 1, 0 ) # Create shot chart (offensive half only) nba = NBACourt(x_trans=-41.75) fig, ax = plt.subplots(1, 1, figsize=(12, 11)) nba.draw(ax=ax, display_range="offense") nba.heatmap( shot_data["LOC_X"], shot_data["LOC_Y"], values=shot_data["SHOT_RESULT"], ax=ax, alpha=0.75, cmap="hot", binsize=1.5, statistic="mean", zorder=11 ) plt.title("Ayo Dosunmu - 2021-22 Shot Chart", fontsize=16) plt.show() ``` -------------------------------- ### Draw NBA Court with SportyPy Source: https://github.com/sportsdataverse/sportypy/blob/main/README.md This snippet demonstrates how to draw a standard NBA basketball court using the NBACourt class from the sportypy.surfaces.basketball module. It requires no specific input data, only the instantiation and drawing of the court object. ```python from sportypy.surfaces.basketball import NBACourt NBACourt().draw() ``` -------------------------------- ### SportyPy Baseball Field: Check Changable Dimensions Source: https://github.com/sportsdataverse/sportypy/blob/main/docs/_build/html/surfaces/baseball.html This Python function, `cani_change_dimensions`, helps users identify which features of a baseball field can be re-parameterized. It's a utility for customizing field dimensions, acting as a starting point for modifications or when using existing league data. ```python from sportypy.surfaces.baseball import BaseballField field = BaseballField() field.cani_change_dimensions() ``` -------------------------------- ### Visualize NFL Red Zone using sportypy Source: https://github.com/sportsdataverse/sportypy/blob/main/docs/_build/html/_sources/index.md.txt This Python code illustrates how to utilize the `display_range` parameter within sportypy to focus on specific areas of a playing surface, such as the 'red zone' for NFL games. This allows for targeted analysis of data within designated regions. ```python # Import football fields from sportypy.surfaces.football import NFLField # Example usage (assuming NFLField is the class and red zone is a valid display_range) # nfl = NFLField(display_range='red_zone') # nfl.draw() ``` -------------------------------- ### NBA Shot Heatmap Generation with Sportypy Source: https://github.com/sportsdataverse/sportypy/blob/main/docs/index.md Creates an NBA shot heatmap using sportypy and nba_api. It fetches shot data, processes coordinates, and visualizes shot results. Requires pandas, numpy, json, and matplotlib. ```python # Import packages import json import numpy as np import pandas as pd from sportypy.surfaces.basketball import NBACourt from nba_api.stats.endpoints import shotchartdetail import math # Import the math module for trigonometric functions # Make API request response = shotchartdetail.ShotChartDetail( team_id = 0, player_id = 1630245, season_nullable = "2021-22", season_type_all_star = "Regular Season", context_measure_simple = "FGA" ) # Extract the json content content = json.loads(response.get_json()) # Form the data set results = content["resultSets"][0] headers = results["headers"] rows = results["rowSet"] shot_data = pd.DataFrame(rows) shot_data.columns = headers # Rotate the coordinates to align with sportypy convention theta = 0.5 * np.pi shot_data["x_r"] = ( (shot_data["LOC_X"] * math.cos(theta)) - (shot_data["LOC_Y"] * math.sin(theta)) ) shot_data["y_r"] = ( (shot_data["LOC_X"] * math.sin(theta)) + (shot_data["LOC_Y"] * math.cos(theta)) ) # Divide by 10 since NBA API gives coordinates in 1/10 of feet measurements shot_data["LOC_X"] = shot_data["x_r"] / 10.0 shot_data["LOC_Y"] = shot_data["y_r"] / 10.0 # Drop extra columns shot_data.drop(labels = ["x_r", "y_r"], axis = 1) # Create SHOT_RESULT used for heatmapping shot_data["SHOT_RESULT"] = np.where( shot_data["EVENT_TYPE"] == "Made Shot", 1, 0 ) # Define the matplotlib instances to plot onto fig, ax = plt.subplots(1, 1) # Start by instantiating a court class. NBA shot data is what's used, so # an NBA court is selected. The rotation is to display a traditional shot # chart of only the offensive half nba = NBACourt(x_trans = -41.75) ax = nba.draw(display_range = "offense") nba.heatmap( shot_data["LOC_X"], shot_data["LOC_Y"], values = shot_data["SHOT_RESULT"], ax = ax, alpha = 0.75, cmap = "hot" ) ``` -------------------------------- ### Visualize NHL Rink Data with Sportypy Source: https://github.com/sportsdataverse/sportypy/blob/main/README.md This snippet demonstrates how to create visualizations on an NHL rink using the sportypy library. It shows how to draw a rink, add contour plots based on goal data, and generate heatmap and hexbin plots for game events. Dependencies include matplotlib and sportypy. ```python import matplotlib.pyplot as plt from sportypy.surfaces.hockey import NHLRink # Assuming pbp is a pandas DataFrame with columns 'x', 'y', and 'goal' # Example data (replace with your actual data) import pandas as pd pbp = pd.DataFrame({ "x": [i for i in range(10, 90, 5)] * 10, "y": [j for i in range(10) for j in range(10, 60, 5)], "goal": [random.random() for _ in range(80)] }) # Create a matplotlib.Axes object for the test plots to lie on fig, axs = plt.subplots(1, 3, figsize = (14, 8)) # Instantiate an NHL rink nhl = NHLRink() # Draw a rink on each of the three matplotlib.Axes objects defined above # and subset them to only the offensive zone for i in range(3): nhl.draw(ax = axs[i], display_range = "ozone") # Add the contour plot contour_img = nhl.contourf( pbp["x"], pbp["y"], values = pbp["goal"], ax = axs[0], cmap = "bwr", plot_range = "ozone", binsize = 10, levels = 50, statistic = "mean" ) # Add a colorbar legend to the bottom to make the metrics easier to read plt.colorbar(contour_img, ax = axs[0], orientation = "horizontal") # Add the heatmap plot nhl.heatmap( pbp["x"], pbp["y"], values = pbp["goal"], ax = axs[1], cmap = "magma", plot_xlim = (25, 89), # offensive-side blue line to the goal line statistic = "mean", vmax = 0.2, binsize = 3 ) # Add the hexbin plot nhl.hexbin( pbp["x"], pbp["y"], values = pbp["goal"], ax = axs[2], binsize = (8, 12), plot_range = "ozone", zorder = 25, alpha = 0.85 ) plt.show() ``` -------------------------------- ### Create and Draw Custom NCAA Basketball Court Source: https://github.com/sportsdataverse/sportypy/blob/main/docs/_build/html/_sources/index.md.txt This snippet shows how to instantiate and draw a custom NCAA basketball court using sportypy. It involves defining a dictionary of colors for various court features. The resulting court can be displayed using matplotlib. ```python from sportypy.surfaces.basketball import NCAACourt NCAACourt( colors_dict = { "offensive_half_court": "#e8e0d7", "defensive_half_court": "#e8e0d7", "court_apron": "#e84a27", "two_point_range": ["#e8e0d7", "#ffffff66"], "center_circle_fill": "#e8e0d7", "painted_area": ["#e84a27", None], "free_throw_circle_fill": "#e8e0d7", "sideline": "#13294b", "endline": "#13294b", "division_line": "#13294b", "center_circle_outline": "#13294b", "lane_boundary": ["#ffffff", "#ffffff00"], "three_point_line": ["#13294b", "#ffffff"], "free_throw_circle_outline": "#ffffff", "lane_space_mark": "#ffffff", "restricted_arc": "#13294b", "backboard": "#13294b" } ).draw() ``` -------------------------------- ### Draw NBA Court using sportypy Source: https://github.com/sportsdataverse/sportypy/blob/main/docs/_build/html/_sources/index.md.txt This code snippet illustrates how to draw a standard NBA court using the NBACourt class from the sportypy.surfaces.basketball module. The draw() method can be called without arguments to render the default court. ```python # Draw an NBA court from sportypy.surfaces.basketball import NBACourt NBACourt().draw() ``` -------------------------------- ### Draw NFL Red Zone using sportypy Source: https://github.com/sportsdataverse/sportypy/blob/main/docs/_build/html/_sources/index.md.txt This snippet demonstrates how to draw the 'red zone' area of an NFL field using the NFLField class from the sportypy.surfaces.football module. It requires no specific input parameters beyond specifying the display range. ```python from sportypy.surfaces.football import NFLField # Draw the red zone of an NFL field NFLField().draw(display_range = "red zone") ``` -------------------------------- ### NHL Goal Probability Comparison Plot Source: https://context7.com/sportsdataverse/sportypy/llms.txt Compares different visualization methods (contour plot, heatmap, hexbin) for NHL goal probability side-by-side. It loads NHL play-by-play data, processes it to calculate goal events and coordinates, and then generates three distinct plots on a multi-panel figure using NHLRink from sportypy.surfaces.hockey. ```python import pandas as pd import numpy as np import matplotlib.pyplot as plt from sportypy.surfaces.hockey import NHLRink # Load NHL data pbp = pd.read_csv( "https://hockey-data.harryshomer.com/pbp/nhl_pbp20192020.csv.gz", compression="gzip" ) # Process data pbp["goal"] = (pbp["Event"] == "GOAL").astype(int) pbp["x"] = np.abs(pbp["xC"]) pbp["y"] = pbp["yC"] * np.sign(pbp["xC"]) pbp = pbp.loc[ (pbp.Ev_Zone == "Off") & ~pbp["x"].isna() & ~pbp["y"].isna() & (pbp.Event.isin(["GOAL", "SHOT", "MISS"])) ][["x", "y", "goal"]] # Create multi-panel figure fig, axs = plt.subplots(1, 3, figsize=(18, 6)) nhl = NHLRink() # Draw rink on all three panels for i in range(3): nhl.draw(ax=axs[i], display_range="ozone") # Panel 1: Contour plot contour_img = nhl.contourf( pbp["x"], pbp["y"], values=pbp["goal"], ax=axs[0], cmap="bwr", plot_range="ozone", binsize=10, levels=50, statistic="mean" ) axs[0].set_title("Contour Plot", fontsize=14) plt.colorbar(contour_img, ax=axs[0], orientation="horizontal") # Panel 2: Heatmap nhl.heatmap( pbp["x"], pbp["y"], values=pbp["goal"], ax=axs[1], cmap="magma", plot_xlim=(25, 89), statistic="mean", vmax=0.2, binsize=3 ) axs[1].set_title("Heatmap", fontsize=14) # Panel 3: Hexbin nhl.hexbin( pbp["x"], pbp["y"], values=pbp["goal"], ax=axs[2], binsize=(8, 12), plot_range="ozone", cmap="YlOrRd", zorder=25, alpha=0.85 ) axs[2].set_title("Hexbin", fontsize=14) plt.suptitle("NHL Goal Probability - Multiple Visualization Methods", fontsize=16) plt.tight_layout() plt.show() ``` -------------------------------- ### Hockey Rink Utility Functions Source: https://github.com/sportsdataverse/sportypy/blob/main/docs/_build/html/surfaces/hockey.html This section covers utility functions for the Hockey Rink object, including checking which dimensions can be changed, which features can be colored, and querying league plotting availability. ```APIDOC ## Hockey Rink Utility Functions ### Description This section covers utility functions for the Hockey Rink object, including checking which dimensions can be changed, which features can be colored, and querying league plotting availability. ### Functions #### `cani_change_dimensions()` ##### Description Determine what features of the rink can be re-parameterized. This function is a helper function for the user to aid in customizing a rink’s parameters. The printed result of this method will be the names of the features that are able to be reparameterized. This method is also useful when defining new features and using an existing league’s rink dimensions as a starting point. ##### Return Type Nothing, but a message will be printed out. #### `cani_color_features()` ##### Description Determine what features of the rink can be colored. This function is a helper function for the user to aid in plot styling and customization. The printed result of this method will be the names of the features that are able to be colored. ##### Return Type Nothing, but a message will be printed out. #### `cani_plot_leagues(_league_code=None_)` ##### Description Show if a league can be plotted, or what leagues are pre-defined. A user may wish to know if a specific curling league can be plotted. This method allows a user to check if that specific league code comes shipped with `sportypy` for easier plotting (if they provide the league code), or can also show what leagues are available to be plotted. ##### Parameters * **league_code** (_str_ or _None_) – A league code that may or may not be shipped with the package. If the league code is `None`, this will display all leagues that do come shipped with `sportypy`. The default is `None`. ##### Return Type Nothing, but a message will be printed out. ``` -------------------------------- ### Create Hockey Shot Conversion Heatmap using Python Source: https://context7.com/sportsdataverse/sportypy/llms.txt Generates a spatial heatmap of shot conversion rates on an NHL rink. It processes play-by-play data to identify goals and shots, standardizes coordinates, filters for offensive zone shots, and then uses the NHLRink's heatmap function. ```python import pandas as pd import numpy as np import matplotlib.pyplot as plt from sportypy.surfaces.hockey import NHLRink # Load NHL play-by-play data pbp = pd.read_csv( "https://hockey-data.harryshomer.com/pbp/nhl_pbp20192020.csv.gz", compression="gzip" ) # Create goal indicator and standardize coordinates pbp["goal"] = (pbp["Event"] == "GOAL").astype(int) pbp["x"] = np.abs(pbp["xC"]) pbp["y"] = pbp["yC"] * np.sign(pbp["xC"]) # Filter to offensive zone shots only pbp = pbp.loc[ (pbp.Ev_Zone == "Off") & ~pbp["x"].isna() & ~pbp["y"].isna() & (pbp.Event.isin(["GOAL", "SHOT", "MISS"])) ][["x", "y", "goal"]] # Create NHL rink and heatmap nhl = NHLRink() fig, ax = plt.subplots(1, 1, figsize=(10, 8)) nhl.draw(ax=ax, display_range="ozone") nhl.heatmap( pbp["x"], pbp["y"], values=pbp["goal"], ax=ax, cmap="magma", plot_xlim=(25, 89), statistic="mean", vmax=0.2, binsize=3, zorder=11, alpha=0.85 ) plt.title("NHL Shot Conversion Rate by Location (2019-20)") plt.colorbar(ax.collections[0], ax=ax, label="Goal Probability") plt.show() ``` -------------------------------- ### NHL Contour and Heatmap Plots with Sportypy Source: https://github.com/sportsdataverse/sportypy/blob/main/docs/index.md Generates contour and heatmap plots for NHL game data using the sportypy library. It visualizes goal probability and shot statistics on a hockey rink. Requires matplotlib and numpy. ```python # Add the contour plot contour_img = nhl.contourf( pbp["x"], pbp["y"], values = pbp["goal"], ax = axs[0], cmap = "bwr", plot_range = "ozone", binsize = 10, levels = 50, statistic = "mean" ) # Add a colorbar legend to the bottom to make the metrics easier to read plt.colorbar(contour_img, ax = axs[0], orientation = "horizontal") # Add the heatmap plot nhl.heatmap( pbp["x"], pbp["y"], values = pbp["goal"], ax = axs[1], cmap = "magma", plot_xlim = (25, 89), # offensive-side blue line to the goal line statistic = "mean", vmax = 0.2, binsize = 3 ) # Add the hexbin plot nhl.hexbin( pbp["x"], pbp["y"], values = pbp["goal"], ax = axs[2], binsize = (8, 12), plot_range = "ozone", zorder = 25, alpha = 0.85 ) ``` -------------------------------- ### Generate NBA Shot Heatmap with Sportypy and NBA API Source: https://github.com/sportsdataverse/sportypy/blob/main/README.md This code snippet generates an NBA shot heatmap for a specific player and season. It fetches shot data using the nba_api, processes it to align with sportypy conventions, and then visualizes it as a heatmap on an NBA court using sportypy. Dependencies include pandas, numpy, json, matplotlib, nba_api, and sportypy. ```python import json import numpy as np import pandas as pd import math import matplotlib.pyplot as plt from sportypy.surfaces.basketball import NBACourt from nba_api.stats.endpoints import shotchartdetail # Make API request for Ayo Dosunmu's rookie season response = shotchartdetail.ShotChartDetail( team_id = 0, # 0 indicates all teams player_id = 1630245, # Ayo Dosunmu's player ID season_nullable = "2021-22", season_type_all_star = "Regular Season", context_measure_simple = "FGA" ) # Extract the json content content = json.loads(response.get_json()) # Form the data set results = content["resultSets"][0] headers = results["headers"] rows = results["rowSet"] shot_data = pd.DataFrame(rows) shot_data.columns = headers # Rotate the coordinates to align with sportypy convention theta = 0.5 * np.pi shot_data["x_r"] = ( (shot_data["LOC_X"] * math.cos(theta)) - (shot_data["LOC_Y"] * math.sin(theta)) ) shot_data["y_r"] = ( (shot_data["LOC_X"] * math.sin(theta)) + (shot_data["LOC_Y"] * math.cos(theta)) ) # Divide by 10 since NBA API gives coordinates in 1/10 of feet measurements shot_data["LOC_X"] = shot_data["x_r"] / 10.0 shot_data["LOC_Y"] = shot_data["y_r"] / 10.0 # Drop extra columns shot_data = shot_data.drop(labels = ["x_r", "y_r"], axis = 1) # Create SHOT_RESULT used for heatmapping (1 for made shot, 0 for missed) shot_data["SHOT_RESULT"] = np.where( shot_data["EVENT_TYPE"] == "Made Shot", 1, 0 ) # Define the matplotlib instances to plot onto fig, ax = plt.subplots(1, 1) # Instantiate an NBA court class. The rotation is to display a traditional shot # chart of only the offensive half nba = NBACourt(x_trans = -41.75) ax = nba.draw(display_range = "offense") nba.heatmap( shot_data["LOC_X"], shot_data["LOC_Y"], values = shot_data["SHOT_RESULT"], ax = ax, alpha = 0.75, cmap = "hot" ) plt.show() ```