{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.10","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":30573,"databundleVersionId":2683891,"sourceType":"competition"}],"dockerImageVersionId":30145,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_kg_hide-input":true,"_kg_hide-output":true,"execution":{"iopub.status.busy":"2023-11-27T11:02:41.2049Z","iopub.execute_input":"2023-11-27T11:02:41.205652Z","iopub.status.idle":"2023-11-27T11:02:41.216449Z","shell.execute_reply.started":"2023-11-27T11:02:41.205603Z","shell.execute_reply":"2023-11-27T11:02:41.215443Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!wget http://bit.ly/3ZLyF82 -O CSS.css -q\n    \nfrom IPython.core.display import HTML\nwith open('./CSS.css', 'r') as file:\n    custom_css = file.read()\n\nHTML(custom_css)","metadata":{"execution":{"iopub.status.busy":"2023-11-27T11:02:41.347234Z","iopub.execute_input":"2023-11-27T11:02:41.348302Z","iopub.status.idle":"2023-11-27T11:02:42.571949Z","shell.execute_reply.started":"2023-11-27T11:02:41.348244Z","shell.execute_reply":"2023-11-27T11:02:42.571109Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%matplotlib inline\nfrom IPython.core.display import display, HTML, Javascript\n\nhtml_contents =\"\"\"\n<!DOCTYPE html>\n<html lang=\"en\">\n    <head>\n        <link rel=\"stylesheet\" href=\"https://www.w3schools.com/w3css/4/w3.css\">\n        <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css?family=Raleway\">\n        <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css?family=Roboto\">\n        <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css?family=Verdana\">\n        <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css?family=Open Sans\">\n        <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\">\n        <style>\n        .title-section{\n            font-family: \"Roboto\", Verdana, sans-serif;\n            font-weight: bold;\n            color: \"#6A8CAF\";\n            letter-spacing: 6px;\n        }\n        hr { border: 1px solid #E58F65 !important;\n             color: #E58F65 !important;\n             background: #E58F65 !important;\n           }\n        body {\n            font-family: \"Verdana\", sans-serif;\n            }        \n        </style>\n    </head>    \n</html>\n\"\"\"\n\nHTML(html_contents)\n\n","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-11-27T11:02:42.574196Z","iopub.execute_input":"2023-11-27T11:02:42.574871Z","iopub.status.idle":"2023-11-27T11:02:42.587502Z","shell.execute_reply.started":"2023-11-27T11:02:42.574833Z","shell.execute_reply":"2023-11-27T11:02:42.586505Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <span class=\"title-section w3-xxlarge\" style=\"color:#DC143C\" id=\"codebook\">0.NFL - National Football League - An Introduction </span>\n","metadata":{}},{"cell_type":"markdown","source":"| NFL Logo | NFL Team Locations |\n| :---: | :-----: |\n| ![NFL](https://upload.wikimedia.org/wikipedia/en/thumb/a/a2/National_Football_League_logo.svg/188px-National_Football_League_logo.svg.png) |   ![NFL Teams](https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/US_National_Football_League_Teams_Location-en.svg/500px-US_National_Football_League_Teams_Location-en.svg.png)   |\n\n\n\n\n\n###### Some Info from Wikipedia\n###### The National Football League (NFL) is a professional American football league consisting of 32 teams, divided equally between the National Football Conference (NFC) and the American Football Conference (AFC). The NFL is one of the four major North American professional sports leagues, the highest professional level of American football in the world.\n\n###### The NFL's eighteen-week regular season runs from early September to early January, with each team playing seventeen games and having one bye week. Following the conclusion of the regular season, seven teams from each conference (four division winners and three wild card teams) advance to the playoffs, a single-elimination tournament culminating in the Super Bowl, which is usually held on the first Sunday in February and is played between the champions of the NFC and AFC. The league is headquartered in New York City.\n\n###### The NFL was formed in 1920 as the American Professional Football Association (APFA) before renaming itself the National Football League for the 1922 season. After initially determining champions through end-of-season standings, a playoff system was implemented in 1933 that culminated with the NFL Championship Game until 1966. Following an agreement to merge the NFL with the rival American Football League (AFL), the Super Bowl was first held in 1967 to determine a champion between the best teams from the two leagues and has remained as the final game of each NFL season since the merger was completed in 1970.\n\n###### Today,the NFL has the highest average attendance (67,591) of any professional sports league in the world and is the most popular sports league in the United States. The Super Bowl is also among the biggest club sporting events in the world, with the individual games accounting for many of the most watched television programs in American history and all occupying the Nielsen's Top 5 tally of the all-time most watched U.S. television broadcasts by 2015. The NFL is the wealthiest professional sports league by revenue, and the sports league with the most valuable teams.","metadata":{}},{"cell_type":"markdown","source":"# <span class=\"title-section w3-xxlarge\" style=\"color:#DC143C\" id=\"codebook\">1.Load the Libraries </span>\n","metadata":{}},{"cell_type":"code","source":"import seaborn as sns\nimport plotly.express as px\nimport matplotlib.pyplot as plt\n","metadata":{"execution":{"iopub.status.busy":"2023-11-27T11:02:42.58922Z","iopub.execute_input":"2023-11-27T11:02:42.590276Z","iopub.status.idle":"2023-11-27T11:02:45.067569Z","shell.execute_reply.started":"2023-11-27T11:02:42.590226Z","shell.execute_reply":"2023-11-27T11:02:45.06646Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plays = '../input/nfl-big-data-bowl-2022/plays.csv'\nplays_df = pd.read_csv(plays)","metadata":{"execution":{"iopub.status.busy":"2023-11-27T11:02:45.069768Z","iopub.execute_input":"2023-11-27T11:02:45.070087Z","iopub.status.idle":"2023-11-27T11:02:45.266063Z","shell.execute_reply.started":"2023-11-27T11:02:45.070046Z","shell.execute_reply":"2023-11-27T11:02:45.264936Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <span class=\"title-section w3-xxlarge\" style=\"color:#DC143C\" id=\"codebook\">2.Check the Datasets </span>\n","metadata":{}},{"cell_type":"code","source":"def disp(data,num):\n    print(data.shape)\n    print(data.columns)\n    print(\"*\"*num)\n    print(data.describe())\n    print(\"=\"*num)\n    return data.head(num)","metadata":{"execution":{"iopub.status.busy":"2023-11-27T11:02:45.267765Z","iopub.execute_input":"2023-11-27T11:02:45.268088Z","iopub.status.idle":"2023-11-27T11:02:45.27422Z","shell.execute_reply.started":"2023-11-27T11:02:45.268007Z","shell.execute_reply":"2023-11-27T11:02:45.273199Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(disp(plays_df,20))","metadata":{"execution":{"iopub.status.busy":"2023-11-27T11:02:45.275604Z","iopub.execute_input":"2023-11-27T11:02:45.275892Z","iopub.status.idle":"2023-11-27T11:02:45.386377Z","shell.execute_reply.started":"2023-11-27T11:02:45.275857Z","shell.execute_reply":"2023-11-27T11:02:45.385243Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plays_df.fillna(0)","metadata":{"execution":{"iopub.status.busy":"2023-11-27T11:02:45.388548Z","iopub.execute_input":"2023-11-27T11:02:45.388904Z","iopub.status.idle":"2023-11-27T11:02:45.468896Z","shell.execute_reply.started":"2023-11-27T11:02:45.388854Z","shell.execute_reply":"2023-11-27T11:02:45.467895Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <span class=\"title-section w3-xxlarge\" style=\"color:#DC143C\" id=\"codebook\">3.Let us do some basic Visualization using Matplotlib and Seaborn </span>\n","metadata":{}},{"cell_type":"code","source":"\n# Import necessary auxiliary stuffs\nfrom matplotlib import gridspec, ticker\n\n# Define size and grid spec\nfig = plt.figure(figsize=(30, 20), constrained_layout=False)\ngs = gridspec.GridSpec(3, 3, figure=fig)\nplt.xticks(rotation=90)\n\n# Make plot to put in first row, rightmost column\nax = fig.add_subplot(gs[1, 2])\nsns.regplot(data = plays_df, x = 'kickReturnYardage', y = 'kickLength',\n            ax = ax, lowess = True,\n            scatter_kws = {'alpha': 0.005, 'color': 'green'},\n            line_kws = {'color': 'blue'}) \\\n    .set_yscale('log')\n\nax.set(title = 'Play Return Number Vs Penalty Yards Info', xlabel = None)\n\nplt.xticks(rotation=90)\n\n# Make plot to put in second row, rightmost column\nax = fig.add_subplot(gs[0, 2])\nsns.boxenplot(data = plays_df, x = 'possessionTeam', y = 'penaltyYards', ax = ax) \\\n    .set_yscale('log')\nax.set(title = 'Penalty Yardage by Special Teams', xlabel = None)\nplt.xticks(rotation=90)\n\n# Make plot to put in third row, rightmost column\nax = fig.add_subplot(gs[2, 2])\nsns.boxenplot(data = plays_df, x = 'possessionTeam', y = 'absoluteYardlineNumber', ax = ax) \\\n    .set_yscale('log')\nax.set(title = 'Absolute Yardline Number for Special Teams Returns', xlabel = None)\nplt.xticks(rotation=90)\n\n# Make plot to put in third row, center column\nax = fig.add_subplot(gs[2, 0])\nsns.regplot(data = plays_df, y = 'kickReturnYardage', x = 'kickLength',\n            ax = ax, lowess = True,\n            scatter_kws = {'alpha': 0.005, 'color': 'magenta'},\n            line_kws = {'color': 'blue'}) \\\n    .set_yscale('log')\nax.set(title = 'Kick Length', xlabel = None)\nplt.xticks(rotation=90)\n\n# Make plot to put in third row, leftmost column\nax = fig.add_subplot(gs[2, 1])\nsns.regplot(data = plays_df, x = 'down', y = 'kickReturnYardage',\n            ax = ax, lowess = True,\n            scatter_kws = {'alpha': 0.005, 'color': 'purple'},\n            line_kws = {'color': 'blue'}) \\\n    .set_yscale('log')\nax.set(title = 'Game Down vs Kick Return info', xlabel = None)\nplt.xticks(rotation=90)\n\n# Make plot that spans the remaining grid\nax = fig.add_subplot(gs[0:2, 0:2])\nsns.boxenplot(data = plays_df, x = 'possessionTeam', y = 'kickReturnYardage', ax = ax) \\\n    .set_yscale('log')\nax.set(title = 'Kick Return Yardage by Team', xlabel = None)\nplt.xticks(rotation=60)\n\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2023-11-27T11:02:45.470824Z","iopub.execute_input":"2023-11-27T11:02:45.471129Z","iopub.status.idle":"2023-11-27T11:02:51.033399Z","shell.execute_reply.started":"2023-11-27T11:02:45.471089Z","shell.execute_reply":"2023-11-27T11:02:51.032336Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# Import necessary auxiliary stuffs\nfrom matplotlib import gridspec, ticker\n\n# Define size and grid spec\nfig = plt.figure(figsize=(30, 20), constrained_layout=False)\ngs = gridspec.GridSpec(3, 3, figure=fig)\nplt.xticks(rotation=90)\n\n# Make plot to put in first row, rightmost column\nax = fig.add_subplot(gs[1, 2])\nsns.regplot(data = plays_df, x = 'kickReturnYardage', y = 'kickLength',\n            ax = ax, lowess = True,\n            scatter_kws = {'alpha': 0.005, 'color': 'green'},\n            line_kws = {'color': 'blue'}) \\\n    .set_yscale('log')\n\nax.set(title = 'Play Return Number Vs Penalty Yards Info', xlabel = None)\n\nplt.xticks(rotation=90)\n\n# Make plot to put in second row, rightmost column\nax = fig.add_subplot(gs[0, 2])\nsns.boxenplot(data = plays_df, x = 'specialTeamsPlayType', y = 'penaltyYards', ax = ax) \\\n    .set_yscale('log')\nax.set(title = 'Penalty Yardage by Special Teams Play Type', xlabel = None)\nplt.xticks(rotation=90)\n\n# Make plot to put in third row, rightmost column\nax = fig.add_subplot(gs[2, 2])\nsns.boxenplot(data = plays_df, x = 'specialTeamsPlayType', y = 'absoluteYardlineNumber', ax = ax) \\\n    .set_yscale('log')\nax.set(title = 'Absolute Yardline Number for Special Teams Play Type Returns', xlabel = None)\nplt.xticks(rotation=90)\n\n# Make plot to put in third row, center column\nax = fig.add_subplot(gs[2, 0])\nsns.regplot(data = plays_df, y = 'kickReturnYardage', x = 'kickLength',\n            ax = ax, lowess = True,\n            scatter_kws = {'alpha': 0.005, 'color': 'magenta'},\n            line_kws = {'color': 'blue'}) \\\n    .set_yscale('log')\nax.set(title = 'Kick Length', xlabel = None)\nplt.xticks(rotation=90)\n\n# Make plot to put in third row, leftmost column\nax = fig.add_subplot(gs[2, 1])\nsns.regplot(data = plays_df, x = 'down', y = 'kickReturnYardage',\n            ax = ax, lowess = True,\n            scatter_kws = {'alpha': 0.005, 'color': 'purple'},\n            line_kws = {'color': 'blue'}) \\\n    .set_yscale('log')\nax.set(title = 'Game Down vs Kick Return info', xlabel = None)\nplt.xticks(rotation=90)\n\n# Make plot that spans the remaining grid\nax = fig.add_subplot(gs[0:2, 0:2])\nsns.boxenplot(data = plays_df, x = 'specialTeamsPlayType', y = 'kickReturnYardage', ax = ax) \\\n    .set_yscale('log')\nax.set(title = 'Kick Return Yardage by Team Play Types', xlabel = None)\nplt.xticks(rotation=60)\n\n\nplt.show()\n ","metadata":{"execution":{"iopub.status.busy":"2023-11-27T11:02:51.034845Z","iopub.execute_input":"2023-11-27T11:02:51.035165Z","iopub.status.idle":"2023-11-27T11:02:54.253186Z","shell.execute_reply.started":"2023-11-27T11:02:51.035122Z","shell.execute_reply":"2023-11-27T11:02:54.252187Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# Import necessary auxiliary stuffs\nfrom matplotlib import gridspec, ticker\n\n# Define size and grid spec\nfig = plt.figure(figsize=(30, 20), constrained_layout=False)\ngs = gridspec.GridSpec(3, 3, figure=fig)\nplt.xticks(rotation=90)\n\n# Make plot to put in first row, rightmost column\nax = fig.add_subplot(gs[0, 2])\nsns.regplot(data = plays_df, x = 'kickReturnYardage', y = 'kickLength',\n            ax = ax, lowess = True,\n            scatter_kws = {'alpha': 0.005, 'color': 'green'},\n            line_kws = {'color': 'blue'}) \\\n    .set_yscale('log')\n\nax.set(title = 'Play Return Number Vs Penalty Yards Info', xlabel = None)\n\nplt.xticks(rotation=90)\n\n# Make plot to put in second row, rightmost column\nax = fig.add_subplot(gs[2, 1])\nsns.boxenplot(data = plays_df, x = 'specialTeamsResult', y = 'penaltyYards', ax = ax) \\\n    .set_yscale('log')\nax.set(title = 'Penalty Yardage by Special Teams Play Results', xlabel = None)\nplt.xticks(rotation=90)\n\n# Make plot to put in third row, rightmost column\nax = fig.add_subplot(gs[2, 0])\nsns.boxenplot(data = plays_df, x = 'specialTeamsResult', y = 'absoluteYardlineNumber', ax = ax) \\\n    .set_yscale('log')\nax.set(title = 'Absolute Yardline Number for Special Teams Play Results - Returns', xlabel = None)\nplt.xticks(rotation=90)\n\n# Make plot to put in third row, center column\nax = fig.add_subplot(gs[2, 2])\nsns.regplot(data = plays_df, y = 'kickReturnYardage', x = 'kickLength',\n            ax = ax, lowess = True,\n            scatter_kws = {'alpha': 0.005, 'color': 'magenta'},\n            line_kws = {'color': 'blue'}) \\\n    .set_yscale('log')\nax.set(title = 'Kick Length', xlabel = None)\nplt.xticks(rotation=90)\n\n# Make plot to put in third row, leftmost column\nax = fig.add_subplot(gs[1, 2])\nsns.regplot(data = plays_df, x = 'down', y = 'kickReturnYardage',\n            ax = ax, lowess = True,\n            scatter_kws = {'alpha': 0.005, 'color': 'purple'},\n            line_kws = {'color': 'blue'}) \\\n    .set_yscale('log')\nax.set(title = 'Game Down vs Kick Return info', xlabel = None)\nplt.xticks(rotation=90)\n\n# Make plot that spans the remaining grid\nax = fig.add_subplot(gs[0:2, 0:2])\nsns.boxenplot(data = plays_df, x = 'specialTeamsResult', y = 'kickReturnYardage', ax = ax) \\\n    .set_yscale('log')\nax.set(title = 'Kick Return Yardage by Team Play Results', xlabel = None)\n#plt.xticks(rotation=60)\nplt.show()\n\n ","metadata":{"execution":{"iopub.status.busy":"2023-11-27T11:02:54.257605Z","iopub.execute_input":"2023-11-27T11:02:54.257968Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ncolor_counts = (plays_df['possessionTeam'].value_counts().reset_index())\ncolor_counts.columns = ['possessionTeam', 'count']\n\norder = color_counts['possessionTeam']\npalette = color_counts['possessionTeam'].replace('other', None) # \"other\" is not a color name\n\nfig = plt.figure(figsize=(15, 8))\ngs = gridspec.GridSpec(1, 3, figure=fig)\n\n# Left plot\nax = fig.add_subplot(gs[0])\nsns.barplot(data = color_counts, x = 'count', y = 'possessionTeam',\n            #palette = palette, \n            ax = ax)\nax.set(title = 'Team KickOffReturns')\nax.set_xlim((0, 900))\nfor p in ax.patches:\n    ax.annotate(f\"{int(p.get_width())}\", xy = (p.get_width(), p.get_y() + 0.5),\n                horizontalalignment = 'left')\n    clr = p.get_facecolor()\n    if clr == (1, 1, 1, 1):\n        # If facecolor is white\n        p.set_edgecolor('magenta')\nax.set_ylabel('')\n\n\n# Right plot\nax = fig.add_subplot(gs[1:3])\nsns.boxenplot(data = plays_df, x = 'kickLength', y = 'possessionTeam',\n              order = order, \n              #palette = palette, \n              ax = ax)\nax.set(title = 'Team Kick Lengths', xscale = 'log')\nax.yaxis.tick_right()\nax.set_ylabel('')\n\nplt.suptitle(\"How teams performed when it comes to kick lengths\", fontsize = 15)\nplt.tight_layout()\nplt.show()\n\n ","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ncolor_counts = (plays_df['specialTeamsPlayType'].value_counts().reset_index())\ncolor_counts.columns = ['specialTeamsPlayType', 'count']\n\norder = color_counts['specialTeamsPlayType']\npalette = color_counts['specialTeamsPlayType'].replace('other', None) # \"other\" is not a color name\n\nfig = plt.figure(figsize=(15, 8))\ngs = gridspec.GridSpec(1, 3, figure=fig)\n\n# Left plot\nax = fig.add_subplot(gs[0])\nsns.barplot(data = color_counts, x = 'count', y = 'specialTeamsPlayType',\n            #palette = palette, \n            ax = ax)\nax.set(title = 'Special Teams Play Type KickOffReturns')\nax.set_xlim((0, 8500))\nfor p in ax.patches:\n    ax.annotate(f\"{int(p.get_width())}\", xy = (p.get_width(), p.get_y() + 0.5),\n                horizontalalignment = 'left')\n    clr = p.get_facecolor()\n    if clr == (1, 1, 1, 1):\n        # If facecolor is white\n        p.set_edgecolor('magenta')\nax.set_ylabel('')\n\n\n# Right plot\nax = fig.add_subplot(gs[1:3])\nsns.boxenplot(data = plays_df, x = 'kickLength', y = 'specialTeamsPlayType',\n              order = order, \n              #palette = palette, \n              ax = ax)\nax.set(title = 'Special Team Play Type Kick Lengths', xscale = 'log')\nax.yaxis.tick_right()\nax.set_ylabel('')\n\nplt.suptitle(\"How Special teams performed when it comes to kick lengths\", fontsize = 15)\nplt.tight_layout()\nplt.show()\n\n ","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ncolor_counts = (plays_df['specialTeamsResult'].value_counts().reset_index())\ncolor_counts.columns = ['specialTeamsResult', 'count']\n\norder = color_counts['specialTeamsResult']\npalette = color_counts['specialTeamsResult'].replace('other', None) # \"other\" is not a color name\n\nfig = plt.figure(figsize=(15, 8))\ngs = gridspec.GridSpec(1, 3, figure=fig)\n\n# Left plot\nax = fig.add_subplot(gs[0])\nsns.barplot(data = color_counts, x = 'count', y = 'specialTeamsResult',\n            #palette = palette, \n            ax = ax)\nax.set(title = 'Special Teams Play Result - KickOffReturns')\nax.set_xlim((0, 5600))\nfor p in ax.patches:\n    ax.annotate(f\"{int(p.get_width())}\", xy = (p.get_width(), p.get_y() + 0.5),\n                horizontalalignment = 'left')\n    clr = p.get_facecolor()\n    if clr == (1, 1, 1, 1):\n        # If facecolor is white\n        p.set_edgecolor('magenta')\nax.set_ylabel('')\n\n\n# Right plot\nax = fig.add_subplot(gs[1:3])\nsns.boxenplot(data = plays_df, x = 'kickLength', y = 'specialTeamsResult',\n              order = order, \n              #palette = palette, \n              ax = ax)\nax.set(title = 'Special Team Play Results - Kick Lengths', xscale = 'log')\nax.yaxis.tick_right()\nax.set_ylabel('')\n\nplt.suptitle(\"How Special teams Results Compared when it comes to kick lengths\", fontsize = 15)\nplt.tight_layout()\nplt.show()\n\n ","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <span class=\"title-section w3-xxlarge\" style=\"color:#DC143C\" id=\"codebook\">4.Let us do Visualization Plot.ly and GroupBy </span>\n","metadata":{}},{"cell_type":"code","source":"df_temp = pd.DataFrame(plays_df.groupby(['specialTeamsPlayType']).specialTeamsResult.count())\ndf_temp2 = pd.DataFrame(plays_df.groupby(['specialTeamsResult']).specialTeamsResult.count())\ndf_temp3= pd.DataFrame(plays_df.groupby(['specialTeamsPlayType', 'specialTeamsResult']).count()).reset_index()\ndf_temp=df_temp.rename(columns={\"specialTeamsResult\": \"NumberOfPlays\"})\ndf_temp2=df_temp2.rename(columns={\"specialTeamsResult\": \"NumberOfPlays\"})\ndf_temp=df_temp.fillna(0)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## <span class=\"title-section w3-xlarge\" style=\"color:#DC143C\" id=\"codebook\">4.1.Some Plots based on Number of Special Team plays </span>\n","metadata":{}},{"cell_type":"markdown","source":"</span>\n","metadata":{}},{"cell_type":"code","source":"\nfig = px.box(df_temp, x=\"NumberOfPlays\")\nfig.show()\nfig = px.bar(df_temp, x=\"NumberOfPlays\")\nfig.show()\nfig = px.box(df_temp2, x=\"NumberOfPlays\")\nfig.show()\nfig = px.bar(df_temp2, x=\"NumberOfPlays\")\nfig.show()\nfig = px.bar(df_temp3.sort_values('gameId',ascending=False), x='gameId', y='specialTeamsResult')#, color='specialTeamsPlayType')\nfig.show()\nfig = px.bar(df_temp3.sort_values('gameId',ascending=False), x='gameId', y='specialTeamsResult', color='specialTeamsPlayType')\n\n ","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del df_temp\ndel df_temp3\ndel df_temp2","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## <span class=\"title-section w3-xlarge\" style=\"color:#DC143C\" id=\"codebook\">4.2.Some Plots based on Number of Special Team play Types </span>\n","metadata":{}},{"cell_type":"code","source":"df_temp = pd.DataFrame(plays_df.groupby(['possessionTeam','specialTeamsPlayType']).kickLength.sum())\ndf_temp2 = pd.DataFrame(plays_df.groupby(['possessionTeam','specialTeamsResult']).kickLength.sum())\ndf_temp3= pd.DataFrame(plays_df.groupby(['possessionTeam','specialTeamsPlayType', 'specialTeamsResult']).sum()).reset_index()\ndf_temp=df_temp.fillna(0)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nfig = px.box(df_temp2, x=\"kickLength\")\nfig.show()\nfig = px.bar(df_temp3.sort_values('gameId',ascending=False), x=\"possessionTeam\", y=\"kickLength\" , color='specialTeamsResult')#, color='specialTeamsPlayType')\nfig.show()\nfig = px.bar(df_temp3.sort_values('gameId',ascending=False), x=\"possessionTeam\", y=\"kickLength\" , color='specialTeamsPlayType')\nfig.show()\n ","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del df_temp\ndel df_temp3\ndel df_temp2","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## <span class=\"title-section w3-xlarge\" style=\"color:#DC143C\" id=\"codebook\">4.3.Some Plots based on Number of Special Team Kick Return Yardage </span>\n","metadata":{}},{"cell_type":"code","source":"\ndf_temp = pd.DataFrame(plays_df.groupby(['possessionTeam','specialTeamsPlayType']).kickReturnYardage.sum())\ndf_temp2 = pd.DataFrame(plays_df.groupby(['possessionTeam','specialTeamsResult']).kickReturnYardage.sum())\ndf_temp3= pd.DataFrame(plays_df.groupby(['possessionTeam','specialTeamsPlayType', 'specialTeamsResult']).sum()).reset_index()\ndf_temp=df_temp.fillna(0)\nfig = px.box(df_temp2, x=\"kickReturnYardage\")\nfig.show()\nfig = px.bar(df_temp3.sort_values('gameId',ascending=False), x=\"possessionTeam\", y=\"kickReturnYardage\" , color='specialTeamsResult')\nfig.show()\nfig = px.bar(df_temp3.sort_values('gameId',ascending=False), x=\"possessionTeam\", y=\"kickReturnYardage\" , color='specialTeamsPlayType')\nfig.show()\ndel df_temp\ndel df_temp3\ndel df_temp2\n ","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## <span class=\"title-section w3-xlarge\" style=\"color:#DC143C\" id=\"codebook\">4.4.Statistics based on absoluteYardlineNumber of each team and special team actions </span>\n","metadata":{}},{"cell_type":"code","source":"\ndf_temp = pd.DataFrame(plays_df.groupby(['possessionTeam','specialTeamsPlayType']).absoluteYardlineNumber.count())\ndf_temp2 = pd.DataFrame(plays_df.groupby(['possessionTeam','specialTeamsResult']).absoluteYardlineNumber.count())\ndf_temp3= pd.DataFrame(plays_df.groupby(['possessionTeam','specialTeamsPlayType', 'specialTeamsResult','absoluteYardlineNumber']).count()).reset_index()\ndf_temp=df_temp.fillna(0)\nfig = px.violin(df_temp2, x=\"absoluteYardlineNumber\")\nfig.show()\nfig = px.bar(df_temp3.sort_values('gameId',ascending=False), x=\"possessionTeam\", y=\"absoluteYardlineNumber\" , color='specialTeamsResult')\nfig.show()\nfig = px.bar(df_temp3.sort_values('gameId',ascending=False), x=\"possessionTeam\", y=\"absoluteYardlineNumber\" , color='specialTeamsPlayType')\nfig.show()\ndel df_temp\ndel df_temp3\ndel df_temp2\n\n ","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## <span class=\"title-section w3-xlarge\" style=\"color:#DC143C\" id=\"codebook\">4.5.Some Plots based on Number of Special Team Penalty Yards Impact </span>\n","metadata":{}},{"cell_type":"code","source":"\ndf_temp = pd.DataFrame(plays_df.groupby(['possessionTeam','specialTeamsPlayType']).penaltyYards.count())\ndf_temp2 = pd.DataFrame(plays_df.groupby(['possessionTeam','specialTeamsResult']).penaltyYards.count())\ndf_temp3= pd.DataFrame(plays_df.groupby(['possessionTeam','specialTeamsPlayType', 'specialTeamsResult','penaltyYards']).count()).reset_index()\ndf_temp=df_temp.fillna(0)\nfig = px.violin(df_temp2, x=\"penaltyYards\")\nfig.show()\nfig = px.bar(df_temp3.sort_values('gameId',ascending=False), x=\"possessionTeam\", y=\"penaltyYards\" , color='specialTeamsResult')\nfig.show()\nfig = px.bar(df_temp3.sort_values('gameId',ascending=False), x=\"possessionTeam\", y=\"penaltyYards\" , color='specialTeamsPlayType')\nfig.show()\ndel df_temp\ndel df_temp3\ndel df_temp2\n\n ","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n## <span class=\"title-section w3-xlarge\" style=\"color:#DC143C\" id=\"codebook\">4.6 Let us try some seaborn Pair Plot Charts </span>\n","metadata":{}},{"cell_type":"markdown","source":"\n## <span class=\"title-section w3-large\" style=\"color:#DC143C\" id=\"codebook\">4.6.1 Full seaborn Pair Plot Charts </span>\n","metadata":{}},{"cell_type":"code","source":"sns.pairplot(plays_df, hue=\"possessionTeam\")\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n## <span class=\"title-section w3-large\" style=\"color:#DC143C\" id=\"codebook\">4.6.2 Full seaborn Pair Plot Chart with a histogram in the diagonal plot </span>\n","metadata":{}},{"cell_type":"code","source":"sns.pairplot(plays_df, hue=\"possessionTeam\",diag_kind=\"hist\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n## <span class=\"title-section w3-large\" style=\"color:#DC143C\" id=\"codebook\">4.6.3 Full seaborn Pair Plot Chart with a hue on Possession Time </span>\n","metadata":{}},{"cell_type":"code","source":"sns.pairplot(plays_df, hue=\"possessionTeam\", height=3)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n## <span class=\"title-section w3-large\" style=\"color:#DC143C\" id=\"codebook\">4.6.3 Full seaborn Pair Plot Chart with a hue on Possession Time </span>\n","metadata":{}},{"cell_type":"code","source":"\nsns.pairplot(\n    plays_df,\n    x_vars=[\"possessionTeam\", \"specialTeamsPlayType\", \"specialTeamsResult\"],\n    y_vars=[\"kickLength\", \"penaltyYards\"],\n    hue='possessionTeam',\n)\n\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n## <span class=\"title-section w3-xlarge\" style=\"color:#DC143C\" id=\"codebook\">4.7 A FacetGrid Plot </span>\n","metadata":{}},{"cell_type":"code","source":"\n# Initialize a grid of plots with an Axes for each walk\ngrid = sns.FacetGrid(plays_df, col=\"possessionTeam\", hue=\"kickLength\", palette=\"tab20c\",\n                     col_wrap=4, height=1.5)\n\n# Draw a horizontal line to show the starting point\ngrid.refline(y=0, linestyle=\":\")\n\n# Draw a line plot to show the trajectory of each random walk\ngrid.map(plt.plot, \"penaltyYards\", \"kickReturnYardage\", marker=\"o\")\n\n# Adjust the arrangement of the plots\ngrid.fig.tight_layout(w_pad=1)\n\n ","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n## <span class=\"title-section w3-xlarge\" style=\"color:#DC143C\" id=\"codebook\">4.8 Let us plot some playes from 2018 play dataset </span>","metadata":{}},{"cell_type":"markdown","source":"\n### <span class=\"title-section w3-large\" style=\"color:#DC143C\" id=\"codebook\">4.8.1 Let us load the plays dataset </span>","metadata":{}},{"cell_type":"code","source":"tr_2018 = '../input/nfl-big-data-bowl-2022/tracking2018.csv'\ntracking2018 = pd.read_csv(tr_2018)","metadata":{"_kg_hide-input":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n### <span class=\"title-section w3-large\" style=\"color:#DC143C\" id=\"codebook\">4.8.2 Let us plot the football field </span>","metadata":{}},{"cell_type":"code","source":"#football field - code from  https://www.kaggle.com/jaronmichal/tracking-data-visualization \nimport matplotlib.patches as patches\nfrom matplotlib.patches import Arc\nfrom matplotlib import pyplot as plt\nimport matplotlib.patches as mpatches\n\n# Change size of the figure\nplt.rcParams['figure.figsize'] = [24, 16]\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,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n### <span class=\"title-section w3-large\" style=\"color:#DC143C\" id=\"codebook\">4.8.3 Plot a play for different roles</span>","metadata":{}},{"cell_type":"code","source":"from cycler import cycler\ncustom_cycler = (cycler(color=['b','k','m','g']))","metadata":{"_kg_hide-input":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plot_play(df, gameId, position):\n    fig, ax = drawPitch(100, 54)\n    ax.set_prop_cycle(custom_cycler)\n    df.query('gameId == ' + gameId + ' and position == \"' + position +  '\"').groupby('team').plot(x='x', y='y', ax=ax, style='.')\n    plt.title(' Plotting for gameId == ' + gameId + ' and position == \"' + position +  '\"',fontsize=36,ha='center')\n    plt.legend().remove()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"poslist = [\"CB\",\"OLB\",\"WR\",\"RB\",\"TE\",\"LB\",\"ILB\",\"K\",\"P\"]\nfor position in poslist:\n    print('Plotting for a ' + position + ' Postion performance')\n    plot_play(tracking2018,'2018091611', position)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### <span class=\"title-section w3-medium\" style=\"color:#DC143C\" id=\"codebook\">4.8.3.1 Plot a play for Running Backs</span>","metadata":{}},{"cell_type":"code","source":"#fig, ax = plt.subplots(figsize=(12, 8))\nfig, ax = drawPitch(100, 54)\nax.set_prop_cycle(custom_cycler)\n\n\ntracking2018.query('gameId == 2018091611 and position == \"RB\"').groupby('team') \\\n    .plot(x='x', y='y', ax=ax, style='.')\ngameId = \"2018091611\"\nposition = \"Running Back\"\nplt.title(' Plotting for gameId == ' + gameId + ' and position == \"' + position +  '\"',fontsize=36,ha='center')\nplt.legend().remove();","metadata":{"_kg_hide-input":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### <span class=\"title-section w3-medium\" style=\"color:#DC143C\" id=\"codebook\">4.8.3.2 Plot a play for Quarter Backs</span>","metadata":{}},{"cell_type":"code","source":"#fig, ax = plt.subplots(figsize=(12, 8))\nfig, ax = drawPitch(100, 54)\nax.set_prop_cycle(custom_cycler)\n\ntracking2018.query('gameId == 2018091611 and position == \"QB\"').groupby('team') \\\n    .plot(x='x', y='y', ax=ax, style='.')\ngameId = \"2018091611\"\nposition = \"Quarter Back\"\nplt.title(' Plotting for gameId == ' + gameId + ' and position == \"' + position +  '\"',fontsize=36,ha='center')\nplt.legend().remove();","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### <span class=\"title-section w3-medium\" style=\"color:#DC143C\" id=\"codebook\">4.8.3.3 Plot a play for Wide Receiver</span>","metadata":{}},{"cell_type":"code","source":"#fig, ax = plt.subplots(figsize=(12, 8))\nfig, ax = drawPitch(100, 54)\nax.set_prop_cycle(custom_cycler)\n\ntracking2018.query('gameId == 2018091611 and position == \"WR\"').groupby('team') \\\n    .plot(x='x', y='y', ax=ax, style='.')\ngameId = \"2018091611\"\nposition = \"Wide Receiver\"\nplt.title(' Plotting for gameId == ' + gameId + ' and position == \"' + position +  '\"',fontsize=36,ha='center')\nplt.legend().remove();","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### <span class=\"title-section w3-medium\" style=\"color:#DC143C\" id=\"codebook\">4.8.3.4 Plot a play for Center Back</span>","metadata":{}},{"cell_type":"code","source":"#fig, ax = plt.subplots(figsize=(12, 8))\nfig, ax = drawPitch(100, 54)\nax.set_prop_cycle(custom_cycler)\n\ntracking2018.query('gameId == 2018091611 and position == \"CB\"').groupby('team') \\\n    .plot(x='x', y='y', ax=ax, style='.')\ngameId = \"2018091611\"\nposition = \"Centre Back\"\nplt.title(' Plotting for gameId == ' + gameId + ' and position == \"' + position +  '\"',fontsize=36,ha='center')\nplt.legend().remove();","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### <span class=\"title-section w3-medium\" style=\"color:#DC143C\" id=\"codebook\">4.8.3.5 Plot a play for a Kicker</span>","metadata":{}},{"cell_type":"code","source":"#fig, ax = plt.subplots(figsize=(12, 8))\nfig, ax = drawPitch(100, 54)\nax.set_prop_cycle(custom_cycler)\n\n\ntracking2018.query('gameId == 2018091611 and position == \"K\"').groupby('team') \\\n    .plot(x='x', y='y', ax=ax, style='.')\ngameId = \"2018091611\"\nposition = \"Kicker\"\nplt.title(' Plotting for gameId == ' + gameId + ' and position == \"' + position +  '\"',fontsize=36,ha='center')\nplt.legend().remove();","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### <span class=\"title-section w3-medium\" style=\"color:#DC143C\" id=\"codebook\">4.8.3.6 Plot a play for a Punter</span>","metadata":{}},{"cell_type":"code","source":"#fig, ax = plt.subplots(figsize=(12, 8))\nfig, ax = drawPitch(100, 54)\nax.set_prop_cycle(custom_cycler)\n\ntracking2018.query('gameId == 2018091611 and position == \"P\"').groupby('team') \\\n    .plot(x='x', y='y', ax=ax, style='.')\ngameId = \"2018091611\"\nposition = \"Punter\"\nplt.title(' Plotting for gameId == ' + gameId + ' and position == \"' + position +  '\"',fontsize=36,ha='center')\nplt.legend().remove();","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n### <span class=\"title-section w3-large\" style=\"color:#DC143C\" id=\"codebook\">4.8.4 Plot a play for the entire team</span>","metadata":{}},{"cell_type":"code","source":"#fig, ax = plt.subplots(figsize=(12, 8))\nfig, ax = drawPitch(100, 54)\nax.set_prop_cycle(custom_cycler)\nprint('Play Summary for gameId == 2018091611 and playId == 2752')\ntracking2018.query('gameId == 2018091611 and playId == 2752').groupby('team') \\\n    .plot(x='x', y='y', ax=ax, style='.')\ngameId = \"2018091611\"\nplayId = \"2752\"\nplt.title(' Plotting for gameId == ' + gameId + ' and playId == \"' + playId +  '\"',fontsize=36,ha='center')\nplt.legend().remove();","metadata":{"_kg_hide-input":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n### <span class=\"title-section w3-large\" style=\"color:#DC143C\" id=\"codebook\">4.8.5 Plot a play for a Outside Line backer</span>","metadata":{}},{"cell_type":"code","source":"#fig, ax = plt.subplots(figsize=(12, 8))\nfig, ax = drawPitch(100, 54)\nax.set_prop_cycle(custom_cycler)\nprint('Play Summary forgameId == 2018091611 and position == \"OLB\"')\ntracking2018.query('gameId == 2018091611 and position == \"OLB\"').groupby('team') \\\n    .plot(x='x', y='y', ax=ax, style='.')\ngameId = \"2018091611\"\nposition = \"Outside Line Backer\"\nplt.title(' Plotting for gameId == ' + gameId + ' and position == \"' + position +  '\"',fontsize=36,ha='center')\nplt.legend().remove();","metadata":{"_kg_hide-input":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n### <span class=\"title-section w3-large\" style=\"color:#DC143C\" id=\"codebook\">4.8.6 Dynamic Pull down menu</span>\n##### \n###### Code Inspired by https://www.kaggle.com/werooring/nfl-big-data-bowl-basic-eda-for-beginner","metadata":{}},{"cell_type":"code","source":"games_ids = {}\ngames_tracking2018 = tracking2018.groupby(by=[\"gameId\"])\nfor game, data in games_tracking2018:\n    games_ids[game] = list(set(data.playId.tolist()))\n\n    ","metadata":{"_kg_hide-input":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ndef 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","metadata":{"_kg_hide-input":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from matplotlib import animation\nfrom IPython.display import HTML\ndef 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([], [], '>', markersize=15, markerfacecolor=\"r\", markeredgewidth=2, markeredgecolor=\"white\", zorder=7)\n    team_right, = ax.plot([], [], '<', markersize=15, markerfacecolor=\"b\", markeredgewidth=2, markeredgecolor=\"white\", zorder=7)\n    ball, = ax.plot([], [], 'o', markersize=20, 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,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n## <span class=\"title-section w3-xlarge\" style=\"color:#DC143C\" id=\"codebook\">4.9 Animation for a play</span>\n","metadata":{}},{"cell_type":"code","source":"animate_one_play(2018121000, 4281, tracking2018)\ngameid=2018123000\ngamelist=(2018121000,2018121000,2018100704,2018111105,2018091610, 2018110401, 2018100701, 2018123005, 2018102102, 2018121606)\nplays=(3312,241,324,3239,3871,2180,4281,993,1452,1977)","metadata":{"_kg_hide-input":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n## <span class=\"title-section w3-xlarge\" style=\"color:#DC143C\" id=\"codebook\">4.9.1 Select a game</span>\n","metadata":{}},{"cell_type":"code","source":"import ipywidgets as widgets\nfrom ipywidgets import interactive\n\ngames = sorted(tracking2018['gameId'].unique().tolist())\n#games = sorted(df['Asset Type Description'].unique().tolist())\n \ndef view(x=''):\n    return tracking2018[tracking2018['gameId']==x]\n \nw = widgets.Dropdown(options=games,\tdescription='Game:',    disabled=False,)\n\ninteractive(view, x=w)","metadata":{"_kg_hide-input":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"gameid = w.value","metadata":{"_kg_hide-input":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import random\n\n#games = sorted(tracking2018['gameId'].unique().tolist())\nplays = sorted(tracking2018[tracking2018['gameId']==gameid]['playId'])\n","metadata":{"_kg_hide-input":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n## <span class=\"title-section w3-xlarge\" style=\"color:#DC143C\" id=\"codebook\">4.9.2 Random Play animation 1</span>","metadata":{}},{"cell_type":"code","source":"animate_one_play(2018121000, 3312, tracking2018)","metadata":{"_kg_hide-input":true,"_kg_hide-output":false,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n## <span class=\"title-section w3-xlarge\" style=\"color:#DC143C\" id=\"codebook\">4.9.3 Random Play animation 2</span>","metadata":{}},{"cell_type":"code","source":"'''\ngameid = 2018100704\nplayid = 3239\nplayid=random.choice(plays)\nprint('animation for ' , playid)\nanimate_one_play(gameid, plays[playid], tracking2018)\n'''\nanimate_one_play(2018122400, 241, tracking2018)","metadata":{"_kg_hide-input":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n## <span class=\"title-section w3-xlarge\" style=\"color:#DC143C\" id=\"codebook\">4.9.4 Random Play animation 3</span>","metadata":{}},{"cell_type":"code","source":"animate_one_play(2018111105, 3239, tracking2018)","metadata":{"_kg_hide-input":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n## <span class=\"title-section w3-xlarge\" style=\"color:#DC143C\" id=\"codebook\">4.9.5 Random Play animation 4</span>","metadata":{}},{"cell_type":"code","source":"animate_one_play(2018091610, 3871, tracking2018)","metadata":{"_kg_hide-input":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n## <span class=\"title-section w3-xlarge\" style=\"color:#DC143C\" id=\"codebook\">4.9.6 Random Play animation 5</span>","metadata":{}},{"cell_type":"code","source":"animate_one_play(2018110401, 2180, tracking2018)","metadata":{"_kg_hide-input":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n\n## <span class=\"title-section w3-xlarge\" style=\"color:#DC143C\" id=\"codebook\">That's all folks! More will come later. Keep checking and keep learning</span>\n\n![More to come](https://www.lambdatest.com/blog/wp-content/uploads/2019/11/giphy-2.gif)","metadata":{}}]}