{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"<H1>Analysis for the approach of a match<H1>","metadata":{}},{"cell_type":"code","source":"#Imports\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport math\nfrom matplotlib.ticker import MaxNLocator\nimport matplotlib.patches as patches\nfrom matplotlib import animation\nfrom IPython.display import HTML\nimport warnings\nwarnings.filterwarnings('ignore')","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2021-12-06T12:37:33.711693Z","iopub.execute_input":"2021-12-06T12:37:33.712059Z","iopub.status.idle":"2021-12-06T12:37:34.736066Z","shell.execute_reply.started":"2021-12-06T12:37:33.711955Z","shell.execute_reply":"2021-12-06T12:37:34.735278Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Data reader\ngames=pd.read_csv(\"../input/nfl-big-data-bowl-2022/games.csv\",parse_dates=[3,4])  \nPFFScoutingData=pd.read_csv('../input/nfl-big-data-bowl-2022/PFFScoutingData.csv')  \nplayers=pd.read_csv('../input/nfl-big-data-bowl-2022/players.csv')  \nplays=pd.read_csv(\"../input/nfl-big-data-bowl-2022/plays.csv\")  \ntracking2020=pd.read_csv('../input/nfl-big-data-bowl-2022/tracking2020.csv')  ","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2021-12-06T12:37:34.737854Z","iopub.execute_input":"2021-12-06T12:37:34.738177Z","iopub.status.idle":"2021-12-06T12:38:14.205261Z","shell.execute_reply.started":"2021-12-06T12:37:34.738134Z","shell.execute_reply":"2021-12-06T12:38:14.204428Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<H3>Select your rival<H3>","metadata":{}},{"cell_type":"code","source":"rival='ATL'","metadata":{"execution":{"iopub.status.busy":"2021-12-06T12:38:14.20665Z","iopub.execute_input":"2021-12-06T12:38:14.206866Z","iopub.status.idle":"2021-12-06T12:38:14.210287Z","shell.execute_reply.started":"2021-12-06T12:38:14.206842Z","shell.execute_reply":"2021-12-06T12:38:14.209721Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#We calculate the final result including the points of the play\nplays = pd.merge(games, plays, on=\"gameId\", how=\"inner\")\nconditions = [\n    (plays[\"specialTeamsResult\"]==\"Kick Attempt Good\") & (plays[\"specialTeamsPlayType\"]==\"Extra Point\") & (plays[\"possessionTeam\"]==plays[\"homeTeamAbbr\"]),\n    (plays[\"specialTeamsResult\"]==\"Kick Attempt Good\") & (plays[\"specialTeamsPlayType\"]==\"Field Goal\") & (plays[\"possessionTeam\"]==plays[\"homeTeamAbbr\"]),\n    (plays[\"specialTeamsResult\"]==\"Kick Attempt Good\") & (plays[\"specialTeamsPlayType\"]==\"Extra Point\") & (plays[\"possessionTeam\"]!=plays[\"homeTeamAbbr\"]),\n    (plays[\"specialTeamsResult\"]==\"Kick Attempt Good\") & (plays[\"specialTeamsPlayType\"]==\"Field Goal\") & (plays[\"possessionTeam\"]!=plays[\"homeTeamAbbr\"]),\n    True\n    ]\n\nvalues = [1,3,-1,-3,0]\n\nplays[\"points\"] = np.select(conditions, values)\n\nplays[\"preSnapHomeScore\"] = plays[[\"preSnapHomeScore\",\"points\"]].sum(axis=1).where(plays[\"points\"] > 0, plays[\"preSnapHomeScore\"])\nplays[\"points\"]= plays[\"points\"]*-1\nplays[\"preSnapVisitorScore\"] = plays[[\"preSnapVisitorScore\",\"points\"]].sum(axis=1).where(plays[\"points\"] > 0, plays[\"preSnapVisitorScore\"])","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2021-12-06T12:38:14.212002Z","iopub.execute_input":"2021-12-06T12:38:14.212215Z","iopub.status.idle":"2021-12-06T12:38:14.319092Z","shell.execute_reply.started":"2021-12-06T12:38:14.212188Z","shell.execute_reply":"2021-12-06T12:38:14.318343Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#We select the opponent's games and fields of interest\ninfoGames = plays[ (plays[\"homeTeamAbbr\"] == rival) | (plays[\"visitorTeamAbbr\"]== rival)]","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2021-12-06T12:38:14.320221Z","iopub.execute_input":"2021-12-06T12:38:14.320584Z","iopub.status.idle":"2021-12-06T12:38:14.333005Z","shell.execute_reply.started":"2021-12-06T12:38:14.320551Z","shell.execute_reply":"2021-12-06T12:38:14.332228Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<H2>1. General information of defeats and victories of the opponent<H2>","metadata":{}},{"cell_type":"code","source":"#We select the last play to keep the las result\nidx1 = infoGames.groupby([\"gameId\"])[\"playId\"].transform(max) == infoGames[\"playId\"]\nfinalResult = infoGames[idx1]\n\n#We create the field \"home/visitor\"\nfinalResult[\"HomeVisitor\"] = [\"Home\" if club==rival else \"Visitor\" for club in finalResult[\"homeTeamAbbr\"]]\n\n#We check whether you have won or lost.\ndef victory(row):\n    if row[\"HomeVisitor\"]==\"Visitor\" and row[\"preSnapHomeScore\"]>row[\"preSnapVisitorScore\"]:\n        return \"Defeat\" \n    elif row[\"HomeVisitor\"]==\"Visitor\" and row[\"preSnapHomeScore\"]<row[\"preSnapVisitorScore\"]:\n        return \"Victory\" \n    elif row[\"HomeVisitor\"]==\"Home\" and row[\"preSnapHomeScore\"]>row[\"preSnapVisitorScore\"]:\n        return \"Victory\"\n    elif row[\"HomeVisitor\"]==\"Home\" and row[\"preSnapHomeScore\"]<row[\"preSnapVisitorScore\"]:\n        return \"Defeat\"\n    else:\n        return \"Draw\" \nfinalResult[\"Result\"] = finalResult.apply(victory, axis=1)\n\n\n#We select the fields we need for the chart\nfinalResult = finalResult[[\"season\",\"HomeVisitor\",\"Result\"]]\n\n#We add a column with 1 to calculate the total of wins, losses and draws\nfinalResult['total'] = 1\n\n#We calculate the total of victories, defeats and draws grouping by season, HomeVisitor, Result\nfinalResult['Sum'] = finalResult['total'].groupby([finalResult['season'],finalResult['HomeVisitor'],finalResult['Result']]).transform('sum')\n\n#We delete the duplicate rows and select the ones we need to make the table\nfinalResult = finalResult.drop_duplicates()\nfinalResult = finalResult[[\"season\",\"HomeVisitor\",\"Result\",\"Sum\"]]\n\n#We draw the table modifying the labels\nplot1 = sns.catplot(kind='bar', data=finalResult, col='season', x='HomeVisitor', y='Sum', hue='Result', estimator=sum, ci=None,\n            order=sorted(finalResult.HomeVisitor.unique()), col_order=sorted(finalResult.season.unique()))\nplot1.set_xlabels('Home vs Visitor', fontsize=15) # not set_label\nplot1.set_ylabels('Frequency', fontsize=15)\nplt.show()","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2021-12-06T12:38:14.336268Z","iopub.execute_input":"2021-12-06T12:38:14.336808Z","iopub.status.idle":"2021-12-06T12:38:15.116088Z","shell.execute_reply.started":"2021-12-06T12:38:14.336773Z","shell.execute_reply":"2021-12-06T12:38:15.115206Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<H2>2. Type of kickoff in the last season<H2>","metadata":{}},{"cell_type":"code","source":"Games = infoGames[[\"gameId\",\"season\",\"playId\",\"possessionTeam\"]]\nGames2020 = Games[(Games[\"possessionTeam\"]==rival) & (Games[\"season\"]==2020)]\nPFFSD_filtered = PFFScoutingData[[\"gameId\",\"playId\",\"kickType\"]]\nGames_TypeKick = pd.merge(Games2020, PFFSD_filtered, on=[\"gameId\",\"playId\"], how=\"inner\")\nkick= Games_TypeKick.groupby([\"kickType\"]).size()\nsizes = ((kick / kick.sum()) * 100).to_list()\nlabels = kick.index.to_list()\nlabels = [f'{l}, {s:0.1f}%' for l, s in zip(labels, sizes)]\nplot2 = plt.pie(kick)\nplt.legend(bbox_to_anchor=(0.9, 0.9), loc='upper left', labels=labels)\nplt.show()","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2021-12-06T12:38:15.117576Z","iopub.execute_input":"2021-12-06T12:38:15.118077Z","iopub.status.idle":"2021-12-06T12:38:15.28802Z","shell.execute_reply.started":"2021-12-06T12:38:15.118042Z","shell.execute_reply":"2021-12-06T12:38:15.287282Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<H2>3. Games played by each player in the last season. See which player is more important in the team.<H2>","metadata":{}},{"cell_type":"code","source":"GamesPlayed=infoGames[[\"gameId\",\"homeTeamAbbr\"]]\nGamesPlayed[\"team\"]=np.where(GamesPlayed['homeTeamAbbr']== rival, \"home\", \"visitor\")\nGamesPlayed=GamesPlayed.drop_duplicates()\ntracking2020_aux=tracking2020[[\"gameId\",\"nflId\",\"team\"]]\ntracking2020_aux=tracking2020_aux.groupby([\"gameId\",\"nflId\",\"team\"]).count().reset_index()\nInfoPlayers = pd.merge(GamesPlayed, tracking2020_aux, on=[\"gameId\",\"team\"], how=\"inner\")\nplayersName=players[[\"nflId\",\"Position\",\"displayName\"]]\nplayersInfoName=InfoPlayers.join(playersName.set_index('nflId'), on='nflId')\nplayersInfoName=playersInfoName[[\"displayName\",\"Position\"]]\nplayersInfoName[\"count\"]=1\nplayersInfoName=playersInfoName.groupby([\"displayName\",\"Position\"]).sum().reset_index().sort_values(by=[\"count\"],ascending=False)\nplayersInfoName = playersInfoName.set_axis(['Player Name', 'Position', 'Games Played'], axis=1)\nprint (playersInfoName.to_string(index=False))","metadata":{"scrolled":true,"_kg_hide-input":true,"execution":{"iopub.status.busy":"2021-12-06T12:38:15.289391Z","iopub.execute_input":"2021-12-06T12:38:15.289642Z","iopub.status.idle":"2021-12-06T12:38:17.040211Z","shell.execute_reply.started":"2021-12-06T12:38:15.289614Z","shell.execute_reply":"2021-12-06T12:38:17.039287Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<H2>4. Frequency of the attacking side of the last game. Where they attack the most.<H2>","metadata":{}},{"cell_type":"code","source":"gamesPos = Games[(Games[\"possessionTeam\"]==rival) & (Games[\"gameId\"]==Games.gameId.max())]\nPFFScoutingData_aux = PFFScoutingData[[\"gameId\",\"playId\",\"kickDirectionActual\"]]\ngamesPos_PFFSD = pd.merge(gamesPos, PFFScoutingData_aux, on=[\"gameId\",\"playId\"], how=\"inner\")\ndirectionGames = gamesPos_PFFSD[\"kickDirectionActual\"].value_counts(dropna=True)\nplot3=directionGames.plot.bar(color=[\"orange\",\"blue\",\"green\"])\nplot3.yaxis.set_major_locator(MaxNLocator(integer=True))\nplt.show()","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2021-12-06T12:38:17.041701Z","iopub.execute_input":"2021-12-06T12:38:17.042188Z","iopub.status.idle":"2021-12-06T12:38:17.22543Z","shell.execute_reply.started":"2021-12-06T12:38:17.042155Z","shell.execute_reply":"2021-12-06T12:38:17.224416Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<H2>5. Team that has played in the previous game<H2>","metadata":{}},{"cell_type":"code","source":"lastGame=infoGames[\"gameId\"].max()\nLastGamePlay=games[games[\"gameId\"]==lastGame]\nHomeAway=\"home\"\nif LastGamePlay.homeTeamAbbr.to_string()==rival:\n    HomeAway= \"home\"\nelse: \n    HomeAway= \"away\"\nlastGameInfo=tracking2020[(tracking2020[\"gameId\"]==lastGame) & (tracking2020[\"team\"]==HomeAway)]\nplayersLastGame= lastGameInfo[\"nflId\"].unique()\nListPlayers=players[players.nflId.isin(playersLastGame)]\nListPlayers=ListPlayers.drop([\"nflId\"],axis=1).sort_values(\"Position\")\nListPlayers[\"age\"]= (pd.Timestamp('now')-pd.to_datetime(ListPlayers[\"birthDate\"], format='%Y-%m-%d')).astype('<m8[Y]')\nListPlayers=ListPlayers.drop([\"birthDate\"],axis=1)\nprint(ListPlayers.to_string(index=False))","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2021-12-06T12:38:17.227964Z","iopub.execute_input":"2021-12-06T12:38:17.22821Z","iopub.status.idle":"2021-12-06T12:38:19.144119Z","shell.execute_reply.started":"2021-12-06T12:38:17.228178Z","shell.execute_reply":"2021-12-06T12:38:19.143274Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<H2>6. Age distribution of the players from the previous game<H2>","metadata":{}},{"cell_type":"code","source":"axAge = sns.distplot(ListPlayers[\"age\"])\naxAge.set(xticks=list(range(18,38)))\naxAge.set_title('Players age Distribution')\nplt.show()","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2021-12-06T12:38:19.145826Z","iopub.execute_input":"2021-12-06T12:38:19.146382Z","iopub.status.idle":"2021-12-06T12:38:19.458056Z","shell.execute_reply.started":"2021-12-06T12:38:19.14634Z","shell.execute_reply":"2021-12-06T12:38:19.457197Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<H2>7. Weight distribution of the players from the previous game<H2>","metadata":{}},{"cell_type":"code","source":"axWeight = sns.distplot(ListPlayers[\"weight\"])\naxWeight.set_title('Players weight Distribution')\nplt.show()","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2021-12-06T12:38:19.459379Z","iopub.execute_input":"2021-12-06T12:38:19.459721Z","iopub.status.idle":"2021-12-06T12:38:19.702184Z","shell.execute_reply.started":"2021-12-06T12:38:19.459687Z","shell.execute_reply":"2021-12-06T12:38:19.701316Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<H2>8. Graph of the points scored for and against in each quarter. See which times he suffers the most and where he is strongest<H2>","metadata":{}},{"cell_type":"code","source":"#We select the matches of the last season with the fields of interest (We reuse the infoGames variable)\npointsQuarter = infoGames[infoGames[\"season\"]==2020]\npointsQuarter = pointsQuarter[[\"gameId\",\"playId\",\"quarter\",\"homeTeamAbbr\",\"visitorTeamAbbr\",\"preSnapHomeScore\",\"preSnapVisitorScore\"]]\n\n#We filter to keep the score at the end of every quarter\nidx2 = pointsQuarter.groupby([\"gameId\",\"quarter\"])[\"playId\"].transform(max) == pointsQuarter[\"playId\"]\npointsQuarter = pointsQuarter[idx2]\n\npointsHome = pointsQuarter[[\"gameId\",\"quarter\",\"homeTeamAbbr\",\"preSnapHomeScore\"]]\npointsHome = pointsHome.rename({'homeTeamAbbr': 'team', 'preSnapHomeScore': 'score'}, axis=1) \n\npointsVisitor = pointsQuarter[[\"gameId\",\"quarter\",\"visitorTeamAbbr\",\"preSnapVisitorScore\"]]\npointsVisitor = pointsQuarter.rename({'visitorTeamAbbr': 'team', 'preSnapVisitorScore': 'score'}, axis=1) \n\npointsGame = pd.concat([pointsHome, pointsVisitor]).reset_index(drop=True)\npointsGame = pointsGame.rename(columns={'gameId':'Date'})\nwidth=int(len(pointsGame[\"Date\"].drop_duplicates())/4)\n\nplot4= sns.relplot(\n    data=pointsGame, x=\"quarter\", y=\"score\",\n    col=\"Date\", hue=\"team\", style=\"team\", col_wrap=width,\n    kind=\"line\",\n)\nplot4.set( xlabel = \"Quarter\", ylabel = \"Score\", xticks=([1,2,3,4]))\nplot4._legend.set_title(\"Team\")\nplt.show()","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2021-12-06T12:38:19.703416Z","iopub.execute_input":"2021-12-06T12:38:19.703645Z","iopub.status.idle":"2021-12-06T12:38:23.749858Z","shell.execute_reply.started":"2021-12-06T12:38:19.703618Z","shell.execute_reply":"2021-12-06T12:38:23.749176Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<H2>9. Match to analyze<H2>","metadata":{}},{"cell_type":"markdown","source":"<H3>Select the match<H3>","metadata":{}},{"cell_type":"code","source":"game=2021010310","metadata":{"execution":{"iopub.status.busy":"2021-12-06T12:38:23.750936Z","iopub.execute_input":"2021-12-06T12:38:23.751243Z","iopub.status.idle":"2021-12-06T12:38:23.754527Z","shell.execute_reply.started":"2021-12-06T12:38:23.751215Z","shell.execute_reply":"2021-12-06T12:38:23.753924Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tracking2020_aux=tracking2020[tracking2020[\"gameId\"]==game]","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2021-12-06T12:38:23.755804Z","iopub.execute_input":"2021-12-06T12:38:23.756276Z","iopub.status.idle":"2021-12-06T12:38:23.781339Z","shell.execute_reply.started":"2021-12-06T12:38:23.756243Z","shell.execute_reply":"2021-12-06T12:38:23.780709Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<H3>Game play log<H3>","metadata":{}},{"cell_type":"code","source":"listGames=plays[plays[\"gameId\"]==game]\nlistGames=listGames[[\"playId\",\"quarter\",\"possessionTeam\",\"specialTeamsPlayType\",\"specialTeamsResult\"]]\nprint(listGames.to_string(index=False))","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2021-12-06T12:38:23.782246Z","iopub.execute_input":"2021-12-06T12:38:23.783009Z","iopub.status.idle":"2021-12-06T12:38:23.795228Z","shell.execute_reply.started":"2021-12-06T12:38:23.782957Z","shell.execute_reply":"2021-12-06T12:38:23.794211Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"This function is taken from the post created by JARON_MICHAL. https://www.kaggle.com/jaronmichal/tracking-data-visualization","metadata":{}},{"cell_type":"code","source":"# Change size of the figure\nplt.rcParams['figure.figsize'] = [12, 8]\ndef drawPitch(width, height, color=\"w\"):\n    fig = plt.figure()\n    ax = plt.axes(xlim=(-10, width + 30), ylim=(-15, height + 5))\n    plt.axis('off')\n\n    # Grass around pitch\n    rect = patches.Rectangle((-10, -5), width + 40, height + 10, linewidth=1, facecolor='#3f995b', capstyle='round')\n    ax.add_patch(rect)\n    ###################\n\n    # Pitch boundaries\n    rect = plt.Rectangle((0, 0), width + 20, height, ec=color, fc=\"None\", lw=2)\n    ax.add_patch(rect)\n    ###################\n\n    # vertical lines - every 5 yards\n    for i in range(21):\n        plt.plot([10 + 5 * i, 10 + 5 * i], [0, height], c=\"w\", lw=2)\n    ###################\n        \n    # distance markers - every 10 yards\n    for yards in range(10, width, 10):\n        yards_text = yards if yards <= width / 2 else width - yards\n        # top markers\n        plt.text(10 + yards - 2, height - 7.5, yards_text, size=15, c=\"w\", weight=\"bold\")\n        # botoom markers\n        plt.text(10 + yards - 2, 7.5, yards_text, size=15, c=\"w\", weight=\"bold\", rotation=180)\n    ###################\n\n    # yards markers - every yard\n    # bottom markers\n    for x in range(20):\n        for j in range(1, 5):\n            plt.plot([10 + x * 5 + j, 10 + x * 5 + j], [1, 3], color=\"w\", lw=2)\n\n    # top markers\n    for x in range(20):\n        for j in range(1, 5):\n            plt.plot([10 + x * 5 + j, 10 + x * 5 + j], [height - 1, height - 3], color=\"w\", lw=2)\n\n    # middle bottom markers\n    y = (height - 18.5) / 2\n    for x in range(20):\n        for j in range(1, 5):\n            plt.plot([10 + x * 5 + j, 10 + x * 5 + j], [y, y + 2], color=\"w\", lw=2)\n\n    # middle top markers\n    for x in range(20):\n        for j in range(1, 5):\n            plt.plot([10 + x * 5 + j, 10 + x * 5 + j], [height - y, height - y - 2], color=\"w\", lw=2)\n    ###################\n\n    # draw home end zone\n    plt.text(2.5, (height - 15) / 2, \"HOME\", size=30, c=\"w\", weight=\"bold\", rotation=90)\n    rect = plt.Rectangle((0, 0), 10, height, ec=color, fc=\"#0064dc\", lw=2)\n    ax.add_patch(rect)\n\n    # draw away end zone    \n    plt.text(111, (height - 15) / 2, \"AWAY\", size=30, c=\"w\", weight=\"bold\", rotation=-90)\n    rect = plt.Rectangle((width + 10, 0), 10, height, ec=color, fc=\"#c80014\", lw=2)\n    ax.add_patch(rect)\n    ###################\n    \n    # draw extra spot point\n    # left\n    y = (height - 3) / 2\n    plt.plot([10 + 2, 10 + 2], [y, y + 3], c=\"w\", lw=2)\n    \n    # right\n    plt.plot([width + 10 - 2, width + 10 - 2], [y, y + 3], c=\"w\", lw=2)\n    ###################\n    \n    # draw goalpost\n    goal_width = 6 # yards\n    y = (height - goal_width) / 2\n    # left\n    plt.plot([0, 0], [y, y + goal_width], \"-\", c=\"y\", lw=10, ms=20)\n    # right\n    plt.plot([width + 20, width + 20], [y, y + goal_width], \"-\", c=\"y\", lw=10, ms=20)\n    \n    return fig, ax","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2021-12-06T12:38:23.796773Z","iopub.execute_input":"2021-12-06T12:38:23.796988Z","iopub.status.idle":"2021-12-06T12:38:23.821522Z","shell.execute_reply.started":"2021-12-06T12:38:23.796963Z","shell.execute_reply":"2021-12-06T12:38:23.820873Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def extract_one_game(game_id, play_id, df):\n    game = df[(df.gameId == game_id) & (df.playId == play_id)]\n    home = {}\n    away = {}\n    balls = []\n    \n    players = game.sort_values(['frameId'], ascending=True).groupby('nflId')\n    for id, dx in players:\n        jerseyNumber = int(dx.jerseyNumber.iloc[0])\n        if dx.team.iloc[0] == \"home\":\n            home[jerseyNumber] = list(zip(dx.x.tolist(), dx.y.tolist()))\n        elif dx.team.iloc[0] == \"away\":\n            away[jerseyNumber] = list(zip(dx.x.tolist(), dx.y.tolist()))\n\n\n    ball_df = game.sort_values(['frameId'], ascending=True) \n    ball_df = ball_df[ball_df.team == \"football\"]\n    balls = list(zip(ball_df.x.tolist(), ball_df.y.tolist()))\n    return home, away, balls\n\n","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2021-12-06T12:38:23.822594Z","iopub.execute_input":"2021-12-06T12:38:23.822809Z","iopub.status.idle":"2021-12-06T12:38:23.839238Z","shell.execute_reply.started":"2021-12-06T12:38:23.822783Z","shell.execute_reply":"2021-12-06T12:38:23.838584Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def animate_one_play(game_id, play_id, df):\n    fig, ax = drawPitch(100, 53.3)\n    \n    home, away, balls = extract_one_game(game_id, play_id, df)\n\n    team_left, = ax.plot([], [], 'o', markersize=20, markerfacecolor=\"r\", markeredgewidth=2, markeredgecolor=\"white\", zorder=7)\n    team_right, = ax.plot([], [], 'o', markersize=20, markerfacecolor=\"b\", markeredgewidth=2, markeredgecolor=\"white\", zorder=7)\n    ball, = ax.plot([], [], 'o', markersize=10, markerfacecolor=\"black\", markeredgewidth=2, markeredgecolor=\"white\", zorder=7)\n    drawings = [team_left, team_right, ball]\n\n    def init():\n        team_left.set_data([], [])\n        team_right.set_data([], [])\n        ball.set_data([], [])\n        return drawings\n\n    def draw_teams(i):\n        X = []\n        Y = []\n        for k, v in home.items():\n            x, y = v[i]\n            X.append(x)\n            Y.append(y)\n        team_left.set_data(X, Y)\n        \n        X = []\n        Y = []\n        for k, v in away.items():\n            x, y = v[i]\n            X.append(x)\n            Y.append(y)\n        team_right.set_data(X, Y)\n\n    def animate(i):\n        draw_teams(i)\n        \n        x, y = balls[i]\n        ball.set_data([x, y])\n        return drawings\n    \n    # !May take a while!\n    anim = animation.FuncAnimation(fig, animate, init_func=init,\n                                   frames=len(balls), interval=100, blit=True)\n\n    return HTML(anim.to_html5_video())","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2021-12-06T12:38:23.840281Z","iopub.execute_input":"2021-12-06T12:38:23.840532Z","iopub.status.idle":"2021-12-06T12:38:23.854475Z","shell.execute_reply.started":"2021-12-06T12:38:23.840502Z","shell.execute_reply":"2021-12-06T12:38:23.853339Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<H3>Select the play<H3>","metadata":{}},{"cell_type":"code","source":"play=40","metadata":{"execution":{"iopub.status.busy":"2021-12-06T12:38:23.855576Z","iopub.execute_input":"2021-12-06T12:38:23.855911Z","iopub.status.idle":"2021-12-06T12:38:23.87043Z","shell.execute_reply.started":"2021-12-06T12:38:23.855884Z","shell.execute_reply":"2021-12-06T12:38:23.869548Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"animate_one_play(game, play, tracking2020_aux)","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2021-12-06T12:38:23.871479Z","iopub.execute_input":"2021-12-06T12:38:23.87212Z","iopub.status.idle":"2021-12-06T12:38:35.515324Z","shell.execute_reply.started":"2021-12-06T12:38:23.872082Z","shell.execute_reply":"2021-12-06T12:38:35.514347Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}