{"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":"## <center>Imports</center>","metadata":{}},{"cell_type":"code","source":"# Linear Algebra, Data Manipulation\nimport numpy as np\nimport pandas as pd\n\n# Plots\nimport seaborn as sns\npal_hls = sns.hls_palette(100, l=.3, s=.8).as_hex() # Seaborn Color Palette for colors\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nsns.set_style('darkgrid')\n\n# Interactive Plots\nimport plotly.express as px\nfrom plotly.offline import init_notebook_mode\nimport plotly.graph_objects as go\ninit_notebook_mode()\n\n# Ignore Warnings\nimport warnings\nwarnings.filterwarnings(\"ignore\")","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:02.896148Z","iopub.execute_input":"2021-11-24T03:32:02.896830Z","iopub.status.idle":"2021-11-24T03:32:05.665076Z","shell.execute_reply.started":"2021-11-24T03:32:02.896717Z","shell.execute_reply":"2021-11-24T03:32:05.664031Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <center>1. Game Data</center>\n### <b>Game Data:</b> The <i>games.csv</i> contains the teams playing in each game. The key variable is gameId","metadata":{}},{"cell_type":"code","source":"games = pd.read_csv(\"../input/nfl-big-data-bowl-2022/games.csv\")\ngames","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:05.667109Z","iopub.execute_input":"2021-11-24T03:32:05.668039Z","iopub.status.idle":"2021-11-24T03:32:05.719174Z","shell.execute_reply.started":"2021-11-24T03:32:05.667978Z","shell.execute_reply":"2021-11-24T03:32:05.718263Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Make Derative Features (month, day, hour)","metadata":{}},{"cell_type":"code","source":"games[\"month\"] = games[\"gameDate\"].apply(lambda x: int(x.split(\"/\")[0]))\ngames[\"day\"] = games[\"gameDate\"].apply(lambda x: int(x.split(\"/\")[1]))\ngames[\"hour\"] = games[\"gameTimeEastern\"].apply(lambda x: int(x.split(\":\")[0]))","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:05.720352Z","iopub.execute_input":"2021-11-24T03:32:05.720608Z","iopub.status.idle":"2021-11-24T03:32:05.742365Z","shell.execute_reply.started":"2021-11-24T03:32:05.720578Z","shell.execute_reply":"2021-11-24T03:32:05.741113Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Data Visualization","metadata":{}},{"cell_type":"code","source":"def plotlybar(data, column, title):\n    df = pd.DataFrame()\n\n    df[column] = data[column].value_counts().index # Gets all the unique seasons\n    df[\"gamesCount\"] = data[column].value_counts().values # Gets the gamesCount for those unique seasons\n    df[\"percent\"] = round(df.gamesCount / len(data) * 100, 1) # The Percent of games played that season\n\n    # Bar plot using plotly bar plot\n    fig = px.bar(df, \n                y='gamesCount',\n                x=column,\n                text='percent',\n                height=600, width=950,\n                title=f\"<b>{title}</b>\", color=pal_hls[:len(df)])\n    fig.update_traces(texttemplate='%{text}%', textposition='outside') # The text at the top of the bar plot\n    fig.update_layout(\n        xaxis = dict(dtick = 1),\n        showlegend=False) # Fixing the problem with the x ticks here\n    fig.show()","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:05.744426Z","iopub.execute_input":"2021-11-24T03:32:05.745110Z","iopub.status.idle":"2021-11-24T03:32:05.755527Z","shell.execute_reply.started":"2021-11-24T03:32:05.745065Z","shell.execute_reply":"2021-11-24T03:32:05.754625Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plotlybar(games, \"season\", \"Number of Games Played Every Season\")","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:05.757060Z","iopub.execute_input":"2021-11-24T03:32:05.757315Z","iopub.status.idle":"2021-11-24T03:32:06.978741Z","shell.execute_reply.started":"2021-11-24T03:32:05.757284Z","shell.execute_reply":"2021-11-24T03:32:06.977844Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"title_font_dict = {\"fontsize\": 16, \"fontweight\": \"bold\"}\n\nplt.figure(figsize=(10, 5), dpi=100)\nsns.countplot(x='season', data=games, hue='month', lw=2)\nplt.title('Games in Year/Season', fontdict=title_font_dict)\nplt.legend([\"January\", \"September\", \"October\", \"November\", \"December\"],\n               loc='center right', bbox_to_anchor=(1.2, 0.5), ncol=1)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:06.979929Z","iopub.execute_input":"2021-11-24T03:32:06.980145Z","iopub.status.idle":"2021-11-24T03:32:07.342990Z","shell.execute_reply.started":"2021-11-24T03:32:06.980118Z","shell.execute_reply":"2021-11-24T03:32:07.342050Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### As the Years Pass the Number of Games Held Every Year/Season Increased","metadata":{}},{"cell_type":"code","source":"plotlybar(games, \"month\", \"Number of Games Played Every Month\")","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:07.344390Z","iopub.execute_input":"2021-11-24T03:32:07.344655Z","iopub.status.idle":"2021-11-24T03:32:07.445932Z","shell.execute_reply.started":"2021-11-24T03:32:07.344621Z","shell.execute_reply":"2021-11-24T03:32:07.445031Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### The Games were held from Sepetember to January. There are especially many games held in December, and rarely any games held in January","metadata":{}},{"cell_type":"code","source":"plotlybar(games, \"day\", \"Number of Games Held Every Day\")","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:07.447322Z","iopub.execute_input":"2021-11-24T03:32:07.447854Z","iopub.status.idle":"2021-11-24T03:32:07.668047Z","shell.execute_reply.started":"2021-11-24T03:32:07.447767Z","shell.execute_reply":"2021-11-24T03:32:07.667102Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Very few Games were Held on 5, 12, 19, 26 and 31 day of the months.","metadata":{}},{"cell_type":"code","source":"plotlybar(games, \"gameTimeEastern\", \"Number of Games played on different gameTimeEastern\")","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:07.669249Z","iopub.execute_input":"2021-11-24T03:32:07.669461Z","iopub.status.idle":"2021-11-24T03:32:07.817941Z","shell.execute_reply.started":"2021-11-24T03:32:07.669435Z","shell.execute_reply":"2021-11-24T03:32:07.817117Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Most of the Games were Held at 13, 16:25, 20:20, 16:05 and 20:15 gameTime Eastern","metadata":{}},{"cell_type":"code","source":"plotlybar(games, \"hour\", \"Number of Games played on different gameTimeEastern(ignoring minutes)\")","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:07.820801Z","iopub.execute_input":"2021-11-24T03:32:07.821078Z","iopub.status.idle":"2021-11-24T03:32:07.945164Z","shell.execute_reply.started":"2021-11-24T03:32:07.821042Z","shell.execute_reply":"2021-11-24T03:32:07.944421Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### This gives us a better representation and tells us that most of the games started at 13, 16 and 20 hours.","metadata":{}},{"cell_type":"code","source":"plotlybar(games, \"week\", \"Number of Games Held Every week\")","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:07.946248Z","iopub.execute_input":"2021-11-24T03:32:07.946578Z","iopub.status.idle":"2021-11-24T03:32:08.107814Z","shell.execute_reply.started":"2021-11-24T03:32:07.946549Z","shell.execute_reply":"2021-11-24T03:32:08.106723Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <center>2. Player Data</center>\n### <b>Player Data:</b> The <i>players.csv</i> contains player-level information from players that pariticipated in any of the tracking data files. The key variable is nflId","metadata":{}},{"cell_type":"code","source":"players = pd.read_csv('../input/nfl-big-data-bowl-2022/players.csv')\nplayers","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:08.109183Z","iopub.execute_input":"2021-11-24T03:32:08.109420Z","iopub.status.idle":"2021-11-24T03:32:08.142842Z","shell.execute_reply.started":"2021-11-24T03:32:08.109391Z","shell.execute_reply":"2021-11-24T03:32:08.141858Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Convert Height to Centimeters and Weight to Kilograms","metadata":{}},{"cell_type":"code","source":"players_heights = players[\"height\"] # Get the Height data from DataFrame\nplayers_heights = players_heights.apply(lambda x: x.split(\"-\")) # Split the heights by hyphen (\"-\")\n\n# Convert Heights to Centimeters and add them to DataFrame\nplayers[\"height\"] = players_heights.apply(lambda x: int(x[0]) * 12 + int(x[1]) if len(x) == 2 else int(x[0])) * 2.54\n\n# Convert Weights to Kilograms and them to DataFrame\nplayers[\"weight\"] = round(players.weight * 0.453592, 2)\n\nplayers","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:08.144297Z","iopub.execute_input":"2021-11-24T03:32:08.145186Z","iopub.status.idle":"2021-11-24T03:32:08.306608Z","shell.execute_reply.started":"2021-11-24T03:32:08.145143Z","shell.execute_reply":"2021-11-24T03:32:08.305624Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Get Birth Year and Birth Month from the birthDate","metadata":{}},{"cell_type":"code","source":"players[\"birthYear\"] = 0\nplayers[\"birthMonth\"] = 0","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:08.308192Z","iopub.execute_input":"2021-11-24T03:32:08.308715Z","iopub.status.idle":"2021-11-24T03:32:08.322345Z","shell.execute_reply.started":"2021-11-24T03:32:08.308662Z","shell.execute_reply":"2021-11-24T03:32:08.321358Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#There are NA values in birthDate so that we should drop them\nplayers.dropna(subset=[\"birthDate\"], inplace=True)","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:08.323744Z","iopub.execute_input":"2021-11-24T03:32:08.324261Z","iopub.status.idle":"2021-11-24T03:32:08.340985Z","shell.execute_reply.started":"2021-11-24T03:32:08.324221Z","shell.execute_reply":"2021-11-24T03:32:08.340070Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for idx, row in players.iterrows():\n    if len(row['birthDate'].split('/')) == 3: # 05/17/1994 \n        players.loc[idx, 'birthYear'] = row['birthDate'].split('/')[2]\n        players.loc[idx, 'birthMonth'] = row['birthDate'].split('/')[0]\n        \n    elif len(row['birthDate'].split('-')) == 3: # 1995-05-05\n        players.loc[idx, 'birthYear'] = row['birthDate'].split('-')[0]\n        players.loc[idx, 'birthMonth'] = row['birthDate'].split('-')[1]","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:08.342311Z","iopub.execute_input":"2021-11-24T03:32:08.342688Z","iopub.status.idle":"2021-11-24T03:32:09.998844Z","shell.execute_reply.started":"2021-11-24T03:32:08.342642Z","shell.execute_reply":"2021-11-24T03:32:09.997900Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"players","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:09.999973Z","iopub.execute_input":"2021-11-24T03:32:10.000176Z","iopub.status.idle":"2021-11-24T03:32:10.022021Z","shell.execute_reply.started":"2021-11-24T03:32:10.000150Z","shell.execute_reply":"2021-11-24T03:32:10.021306Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig = plt.figure(figsize=(20, 15), dpi=80)\n\nbirth_year_dist = players.birthYear.value_counts().sort_index()\nax1 = fig.add_subplot(221)\nsns.barplot(x=birth_year_dist.index, y=birth_year_dist.values, ax=ax1)\nax1.tick_params(axis='x', rotation=45)\nax1.set_title(\"Birth Year Distribution\", fontdict=title_font_dict)\n\nbirth_month_dist = players.birthMonth.value_counts().sort_index()\nax2 = fig.add_subplot(222)\nsns.barplot(x=birth_month_dist.index, y=birth_month_dist.values, ax=ax2)\nax2.set_title(\"Birth Month Distribution\", fontdict=title_font_dict)\n\nax3 = fig.add_subplot(223)\nsns.histplot(players.weight, ax=ax3)\nax3.set_title(\"Weight(Kg) Distribution\", fontdict=title_font_dict)\n\nax4 = fig.add_subplot(224)\nsns.histplot(players.height, ax=ax4, bins=10)\nax4.set_title(\"Height(cm) Distribution\", fontdict=title_font_dict);","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:10.022996Z","iopub.execute_input":"2021-11-24T03:32:10.023684Z","iopub.status.idle":"2021-11-24T03:32:11.570197Z","shell.execute_reply.started":"2021-11-24T03:32:10.023640Z","shell.execute_reply":"2021-11-24T03:32:11.569104Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig = plt.figure(figsize=(20, 12), dpi=80)\ntitle_font_dict = {\"fontsize\": 16, \"fontweight\": \"bold\"}\n\nax1 = fig.add_subplot(211)\nsns.boxplot(players.weight, ax=ax1, width=0.5)\nax1.set_title(\"Weight(Kg) Distribution\", fontdict=title_font_dict)\n\nax2 = fig.add_subplot(212)\nsns.boxplot(players.height, ax=ax2, width=0.5)\nax2.set_title(\"Height(cm) Distribution\", fontdict=title_font_dict);","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:11.571347Z","iopub.execute_input":"2021-11-24T03:32:11.571596Z","iopub.status.idle":"2021-11-24T03:32:12.073759Z","shell.execute_reply.started":"2021-11-24T03:32:11.571565Z","shell.execute_reply":"2021-11-24T03:32:12.072878Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Most of the Players are Born between 1991 and 1997\n#### Most of the Players weight between 80 to 120 kgs\n#### Most of the players have the height between 185cm to 195cm","metadata":{}},{"cell_type":"code","source":"print(f\"Youngest Player Born in: {players.birthYear.max()}\")\nprint(f\"Oldest Player Born in: {players.birthYear.min()}\")","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:12.075096Z","iopub.execute_input":"2021-11-24T03:32:12.075895Z","iopub.status.idle":"2021-11-24T03:32:12.083957Z","shell.execute_reply.started":"2021-11-24T03:32:12.075844Z","shell.execute_reply":"2021-11-24T03:32:12.083088Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(10, 6), dpi=100)\nsns.regplot(x=players.weight, y=players.height, line_kws={\"color\": \"orange\"})\nplt.title(\"Player Weight(Kg) vs Player Height(cm)\");","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:12.085157Z","iopub.execute_input":"2021-11-24T03:32:12.085722Z","iopub.status.idle":"2021-11-24T03:32:12.705848Z","shell.execute_reply.started":"2021-11-24T03:32:12.085685Z","shell.execute_reply":"2021-11-24T03:32:12.704796Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### It seems that players with higher weight tend to be longer and vice versa is also possible","metadata":{}},{"cell_type":"code","source":"# Seeing Which college has given the most number of players\n\ncollege_count = players.collegeName.value_counts()[:25]\n\nfig = px.bar(x=college_count.index, y=college_count.values,\n             labels={\"x\":\"College Name\", \"y\":\"Count\"}, title=\"<b>Players College Count</b>\")\nfig.update_layout(\n  width=1300,\n  height=500,\n)\nfig.show()","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:12.707527Z","iopub.execute_input":"2021-11-24T03:32:12.707858Z","iopub.status.idle":"2021-11-24T03:32:12.783319Z","shell.execute_reply.started":"2021-11-24T03:32:12.707816Z","shell.execute_reply":"2021-11-24T03:32:12.782334Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Alabama College has given the most number of Players","metadata":{}},{"cell_type":"code","source":"position_count = players.Position.value_counts()\n\nfig = px.bar(x=position_count.index, y=position_count.values,\n             labels={\"x\":\"Position\", \"y\":\"Count\"}, title=\"<b>Players Position Count</b>\")\nfig.update_layout(\n  width=1300,\n  height=500,\n)\nfig.show()","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:12.784999Z","iopub.execute_input":"2021-11-24T03:32:12.785298Z","iopub.status.idle":"2021-11-24T03:32:12.858287Z","shell.execute_reply.started":"2021-11-24T03:32:12.785260Z","shell.execute_reply":"2021-11-24T03:32:12.857426Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Highest Number of Players play at WR Positon and very few Players play at HB Position","metadata":{}},{"cell_type":"markdown","source":"# <center>3. Play Data</center>\n### <b>Play Data:</b> The <i>plays.csv</i> file contains play-level information from each game. The key variable are gameId and playId","metadata":{}},{"cell_type":"code","source":"plays = pd.read_csv(\"../input/nfl-big-data-bowl-2022/plays.csv\")\nplays","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:12.859274Z","iopub.execute_input":"2021-11-24T03:32:12.859513Z","iopub.status.idle":"2021-11-24T03:32:13.044654Z","shell.execute_reply.started":"2021-11-24T03:32:12.859479Z","shell.execute_reply":"2021-11-24T03:32:13.043797Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(15, 12))\nsns.heatmap(plays.corr(), annot=True)","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:13.046147Z","iopub.execute_input":"2021-11-24T03:32:13.046467Z","iopub.status.idle":"2021-11-24T03:32:14.804235Z","shell.execute_reply.started":"2021-11-24T03:32:13.046423Z","shell.execute_reply":"2021-11-24T03:32:14.803253Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plays.info()","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:14.805628Z","iopub.execute_input":"2021-11-24T03:32:14.805880Z","iopub.status.idle":"2021-11-24T03:32:14.839809Z","shell.execute_reply.started":"2021-11-24T03:32:14.805837Z","shell.execute_reply":"2021-11-24T03:32:14.838863Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plotlybar(plays, \"quarter\", \"Number of Plays every quater\")","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:14.841156Z","iopub.execute_input":"2021-11-24T03:32:14.841418Z","iopub.status.idle":"2021-11-24T03:32:14.940773Z","shell.execute_reply.started":"2021-11-24T03:32:14.841390Z","shell.execute_reply":"2021-11-24T03:32:14.939860Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plotlybar(plays, \"down\", \"Number of Plays every down\")","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:14.945066Z","iopub.execute_input":"2021-11-24T03:32:14.945336Z","iopub.status.idle":"2021-11-24T03:32:15.046178Z","shell.execute_reply.started":"2021-11-24T03:32:14.945304Z","shell.execute_reply":"2021-11-24T03:32:15.045364Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plotlybar(plays, \"yardsToGo\", \"Number of Plays every yardsToGo\")","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:15.047675Z","iopub.execute_input":"2021-11-24T03:32:15.048161Z","iopub.status.idle":"2021-11-24T03:32:15.297478Z","shell.execute_reply.started":"2021-11-24T03:32:15.048119Z","shell.execute_reply":"2021-11-24T03:32:15.296683Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plotlybar(plays, \"specialTeamsPlayType\", \"Number of Playes per specialTeamsPlayType\")","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:15.299046Z","iopub.execute_input":"2021-11-24T03:32:15.299511Z","iopub.status.idle":"2021-11-24T03:32:15.392639Z","shell.execute_reply.started":"2021-11-24T03:32:15.299466Z","shell.execute_reply":"2021-11-24T03:32:15.391832Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plotlybar(plays, \"possessionTeam\", \"Number of Playes per possessionTeam\")","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:15.394188Z","iopub.execute_input":"2021-11-24T03:32:15.394640Z","iopub.status.idle":"2021-11-24T03:32:15.642616Z","shell.execute_reply.started":"2021-11-24T03:32:15.394594Z","shell.execute_reply":"2021-11-24T03:32:15.641727Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(10, 12), dpi=100)\n\nax1 = plt.subplot(211)\nsns.histplot(plays.kickLength, ax=ax1)\nax1.set_title(\"Kick Length Distribution\", fontdict=title_font_dict)\nax1.set_xticks(np.arange(0, 85, 10));\n\nax2 = plt.subplot(212)\nsns.boxplot(plays.kickLength, ax=ax2, width=0.5)\nax2.set_title(\"Kick Length Distribution\", fontdict=title_font_dict)\nax2.set_xticks(np.arange(0, 85, 10));","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:15.644465Z","iopub.execute_input":"2021-11-24T03:32:15.644756Z","iopub.status.idle":"2021-11-24T03:32:16.301650Z","shell.execute_reply.started":"2021-11-24T03:32:15.644720Z","shell.execute_reply":"2021-11-24T03:32:16.300806Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"columns = [\"quarter\", \"down\", \"preSnapHomeScore\", \"preSnapVisitorScore\", \"kickReturnYardage\", \"kickLength\", \"yardsToGo\", \"kickBlockerId\",\n           \"yardlineNumber\", \"penaltyYards\", \"playResult\"]\n\nplays_temp = plays[columns]\nplays_temp","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:16.302915Z","iopub.execute_input":"2021-11-24T03:32:16.303148Z","iopub.status.idle":"2021-11-24T03:32:16.330671Z","shell.execute_reply.started":"2021-11-24T03:32:16.303118Z","shell.execute_reply":"2021-11-24T03:32:16.329839Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(12, 8), dpi=80)\nsns.heatmap(plays_temp.corr(), annot=True)\nplt.title(\"Correlation Heat Map\", fontdict=title_font_dict);","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:16.332275Z","iopub.execute_input":"2021-11-24T03:32:16.332764Z","iopub.status.idle":"2021-11-24T03:32:17.642854Z","shell.execute_reply.started":"2021-11-24T03:32:16.332720Z","shell.execute_reply":"2021-11-24T03:32:17.642006Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(15, 6), dpi=100)\n\nax1 = plt.subplot(121)\nsns.boxplot(\n    x = plays_temp.quarter,\n    y = plays_temp.preSnapHomeScore,\n    ax=ax1\n)\nax1.set_title(\"quarter vs preSnapHomeScore\", fontdict=title_font_dict)\n\nax2 = plt.subplot(122)\nsns.boxplot(\n    x = plays_temp.quarter,\n    y = plays_temp.preSnapVisitorScore,\n    ax=ax2\n)\nax2.set_title(\"quarter vs preSnapVisitorScore\", fontdict=title_font_dict);","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:17.644400Z","iopub.execute_input":"2021-11-24T03:32:17.644895Z","iopub.status.idle":"2021-11-24T03:32:18.239123Z","shell.execute_reply.started":"2021-11-24T03:32:17.644851Z","shell.execute_reply":"2021-11-24T03:32:18.238163Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(15, 6), dpi=100)\n\nax1 = plt.subplot(121)\nsns.boxplot(\n    x = plays_temp.down,\n    y = plays_temp.kickReturnYardage,\n    ax=ax1\n)\nax1.set_title(\"down vs kickReturnYardage\", fontdict=title_font_dict)\n\nax2 = plt.subplot(122)\nsns.boxplot(\n    x = plays_temp.down,\n    y = plays_temp.kickLength,\n    ax=ax2\n)\nax2.set_title(\"down vs kickLength\", fontdict=title_font_dict);","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:18.240341Z","iopub.execute_input":"2021-11-24T03:32:18.240566Z","iopub.status.idle":"2021-11-24T03:32:18.778627Z","shell.execute_reply.started":"2021-11-24T03:32:18.240537Z","shell.execute_reply":"2021-11-24T03:32:18.777545Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(25, 8))\n\nax1 = plt.subplot(131)\nsns.boxplot(\n    x = plays_temp.yardsToGo,\n    y = plays_temp.kickReturnYardage,\n    ax=ax1\n)\nax1.set_title(\"yardsToGo vs kickReturnYardage\", fontdict=title_font_dict)\n\nax2 = plt.subplot(132)\nsns.boxplot(\n    x = plays_temp.yardsToGo,\n    y = plays_temp.kickLength,\n    ax=ax2\n)\nax2.set_title(\"yardsToGo vs kickLength\", fontdict=title_font_dict);\n\nax3 = plt.subplot(133)\nsns.boxplot(\n    x = plays_temp.yardsToGo,\n    y = plays_temp.kickBlockerId,\n    ax=ax3\n)\nax3.set_title(\"yardsToGo vs kickBlockerId\", fontdict=title_font_dict);","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:18.780038Z","iopub.execute_input":"2021-11-24T03:32:18.780261Z","iopub.status.idle":"2021-11-24T03:32:21.993811Z","shell.execute_reply.started":"2021-11-24T03:32:18.780233Z","shell.execute_reply":"2021-11-24T03:32:21.992847Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(20, 10))\n\nax1 = plt.subplot(121)\nsns.regplot(\n    x = plays_temp.yardlineNumber,\n    y = plays_temp.playResult,\n    ax=ax1, line_kws={\"color\": \"orange\"}, scatter_kws={\"color\": \"#396EB0\"},\n)\nax1.set_title(\"yardlineNumber vs playResult\", fontdict=title_font_dict)\n\nax2 = plt.subplot(122)\nsns.regplot(\n    x = plays_temp.yardlineNumber,\n    y = plays_temp.kickLength,\n    ax=ax2, line_kws={\"color\": \"#396EB0\"}, scatter_kws={\"color\": \"orange\"},\n    marker=\"+\"\n)\nax2.set_title(\"yardlineNumber vs kickLength\", fontdict=title_font_dict);","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:21.994861Z","iopub.execute_input":"2021-11-24T03:32:21.995077Z","iopub.status.idle":"2021-11-24T03:32:24.471235Z","shell.execute_reply.started":"2021-11-24T03:32:21.995042Z","shell.execute_reply":"2021-11-24T03:32:24.470254Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(20, 10))\n\nax1 = plt.subplot(121)\nsns.regplot(\n    x = plays_temp.kickLength,\n    y = plays_temp.kickReturnYardage,\n    ax=ax1, line_kws={\"color\": \"orange\"}, scatter_kws={\"color\": \"#396EB0\"},\n)\nax1.set_title(\"kickLength vs kickReturnYardage\", fontdict=title_font_dict)\n\nax2 = plt.subplot(122)\nsns.regplot(\n    x = plays_temp.kickLength,\n    y = plays_temp.playResult,\n    ax=ax2, line_kws={\"color\": \"#396EB0\"}, scatter_kws={\"color\": \"orange\"},\n    marker=\"+\"\n)\nax2.set_title(\"kickLength vs playResult\", fontdict=title_font_dict);","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:24.480972Z","iopub.execute_input":"2021-11-24T03:32:24.481181Z","iopub.status.idle":"2021-11-24T03:32:26.335949Z","shell.execute_reply.started":"2021-11-24T03:32:24.481155Z","shell.execute_reply":"2021-11-24T03:32:26.334854Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <center>4. Tracking Data</center>","metadata":{}},{"cell_type":"code","source":"tracking2020 = pd.read_csv('../input/nfl-big-data-bowl-2022/tracking2020.csv')\ntracking2020.head()","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:32:26.337372Z","iopub.execute_input":"2021-11-24T03:32:26.337725Z","iopub.status.idle":"2021-11-24T03:33:08.016604Z","shell.execute_reply.started":"2021-11-24T03:32:26.337669Z","shell.execute_reply":"2021-11-24T03:33:08.015749Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Downloading and Saving Field Image for BackGround\nimport urllib.request\nurllib.request.urlretrieve(\"https://upload.wikimedia.org/wikipedia/commons/thumb/c/c5/AmFBfield.svg/1200px-AmFBfield.svg.png\", \"field.png\")\n\nfrom PIL import Image\n#set a local image as a background\nimage_filename = 'field.png'\nplotly_logo = Image.open(image_filename)","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:33:08.017871Z","iopub.execute_input":"2021-11-24T03:33:08.018110Z","iopub.status.idle":"2021-11-24T03:33:08.105220Z","shell.execute_reply.started":"2021-11-24T03:33:08.018080Z","shell.execute_reply":"2021-11-24T03:33:08.104125Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plot_tracking_data(gameId, playId=False, position=False):\n    team_names = [\"home\", \"away\", \"football\"]\n    colors = [\"#396EB0\", \"#116530\", \"red\"]\n    \n    if playId:\n        temp_tracking_df = tracking2020.query(f'gameId == {gameId} and playId == {playId}')\n        teams = 3\n    elif position:\n        temp_tracking_df = tracking2020.query(f'gameId == {gameId} and position == \"{position}\"')\n        teams = 2\n        \n    fig = go.Figure()\n    \n    for i in range (teams):\n        fig.add_trace(go.Scatter(\n            x = temp_tracking_df.query(f\"team == '{team_names[i]}'\").x,\n            y = temp_tracking_df.query(f\"team == '{team_names[i]}'\").y,\n            mode = \"markers\",\n            name=team_names[i],\n            marker=dict(color=colors[i])\n        ))\n        \n    if playId:\n        title = f\"<b>Tracking Data - gameId = {gameId} and playId = {playId}</b>\"\n    elif position:\n        title = f\"<b>Tracking Data - gameId = {gameId} and position = {position}</b>\"\n        \n    fig.update_layout(\n        template=\"plotly_white\",\n        autosize=False,\n        width=1000,\n        height=550,\n        images= [dict(source=plotly_logo,\n                      xref=\"paper\", yref=\"paper\",x=0, y=1, sizex=1, sizey=1,\n                      layer=\"below\", opacity=0.5)],\n        xaxis=dict(showgrid=False),\n        yaxis=dict(showgrid=False),\n        title=title,\n        xaxis_title=\"x\",\n        yaxis_title=\"y\",\n    )\n    fig.show()","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:34:06.631842Z","iopub.execute_input":"2021-11-24T03:34:06.632608Z","iopub.status.idle":"2021-11-24T03:34:06.644578Z","shell.execute_reply.started":"2021-11-24T03:34:06.632558Z","shell.execute_reply":"2021-11-24T03:34:06.643542Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_tracking_data(gameId=2020092707, playId=1186)","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:34:07.226839Z","iopub.execute_input":"2021-11-24T03:34:07.227160Z","iopub.status.idle":"2021-11-24T03:34:07.423385Z","shell.execute_reply.started":"2021-11-24T03:34:07.227121Z","shell.execute_reply":"2021-11-24T03:34:07.422695Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_tracking_data(gameId=2020102600, playId=250)","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:33:08.476050Z","iopub.status.idle":"2021-11-24T03:33:08.476527Z","shell.execute_reply.started":"2021-11-24T03:33:08.476274Z","shell.execute_reply":"2021-11-24T03:33:08.476298Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_tracking_data(gameId=2021010307, playId=2460)","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:33:08.478877Z","iopub.status.idle":"2021-11-24T03:33:08.479338Z","shell.execute_reply.started":"2021-11-24T03:33:08.479097Z","shell.execute_reply":"2021-11-24T03:33:08.479131Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"temp_tracking_df = tracking2020.query(f'gameId == 2021010307 and position == \"RB\"')\n","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:33:08.480846Z","iopub.status.idle":"2021-11-24T03:33:08.481896Z","shell.execute_reply.started":"2021-11-24T03:33:08.481570Z","shell.execute_reply":"2021-11-24T03:33:08.481601Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_tracking_data(gameId=2020102508, position=\"CB\")","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:33:08.483429Z","iopub.status.idle":"2021-11-24T03:33:08.483878Z","shell.execute_reply.started":"2021-11-24T03:33:08.483631Z","shell.execute_reply":"2021-11-24T03:33:08.483652Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_tracking_data(gameId=2020101112, position=\"LB\")","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:33:08.485410Z","iopub.status.idle":"2021-11-24T03:33:08.486208Z","shell.execute_reply.started":"2021-11-24T03:33:08.485948Z","shell.execute_reply":"2021-11-24T03:33:08.485974Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_tracking_data(gameId=2020102507, position=\"RB\")","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:33:08.487478Z","iopub.status.idle":"2021-11-24T03:33:08.488418Z","shell.execute_reply.started":"2021-11-24T03:33:08.488132Z","shell.execute_reply":"2021-11-24T03:33:08.488163Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Animating Tracking Data using Plotly","metadata":{}},{"cell_type":"code","source":"import base64\n\ndef animated_game(gameId, playId, speed):\n    temp_tracking_df = tracking2020[tracking2020['gameId'] == gameId]\n\n    temp_tracking_query = (tracking2020['gameId'] == gameId) & (tracking2020['playId'] == playId)\n\n    temp_tracking_df = (\n        tracking2020[temp_tracking_query][['x', 'y', 'time', 'nflId', 'team', 'displayName']]\n        .fillna(0.)\n        .sort_values(['team', 'time'])\n    )\n\n    fig = px.scatter(\n        temp_tracking_df,\n        x='x',\n        y='y',\n        animation_frame='time',\n        color='team',\n        animation_group=\"nflId\",\n        hover_name=\"displayName\"\n    )\n    fig.update_traces(marker=dict(size=12,line=dict(width=2,color='DarkSlateGrey')),\n                      selector=dict(mode='markers'))\n    fig.update_layout(\n        template=\"plotly_white\",\n        autosize=False,\n        width=1000,\n        height=600,\n        title=f'Animation Every Players in the play {playId} of Game {gameId}',\n        images= [dict(source=plotly_logo,\n                      xref=\"paper\", yref=\"paper\",x=0, y=1, sizex=1, sizey=1,\n                      layer=\"below\", opacity=0.5)],\n        xaxis=dict(showgrid=False),\n        yaxis=dict(showgrid=False)\n    )\n    fig.layout.updatemenus[0].buttons[0].args[1][\"frame\"][\"duration\"] = speed\n    fig.show()","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:33:08.489706Z","iopub.status.idle":"2021-11-24T03:33:08.490639Z","shell.execute_reply.started":"2021-11-24T03:33:08.490361Z","shell.execute_reply":"2021-11-24T03:33:08.490395Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"gameId = 2021010300\nplayId = 40\nspeed = 60\n\nanimated_game(gameId, playId, speed)","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:33:08.492159Z","iopub.status.idle":"2021-11-24T03:33:08.492624Z","shell.execute_reply.started":"2021-11-24T03:33:08.492386Z","shell.execute_reply":"2021-11-24T03:33:08.492410Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"gameId = 2020111510\nplayId = 1987\nspeed = 60\n\nanimated_game(gameId, playId, speed)","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:33:08.494161Z","iopub.status.idle":"2021-11-24T03:33:08.494639Z","shell.execute_reply.started":"2021-11-24T03:33:08.494387Z","shell.execute_reply":"2021-11-24T03:33:08.494413Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"gameId = 2020121302\nplayId = 1320\nspeed = 60\n\nanimated_game(gameId, playId, speed)","metadata":{"execution":{"iopub.status.busy":"2021-11-24T03:33:08.495742Z","iopub.status.idle":"2021-11-24T03:33:08.496292Z","shell.execute_reply.started":"2021-11-24T03:33:08.495990Z","shell.execute_reply":"2021-11-24T03:33:08.496016Z"},"trusted":true},"execution_count":null,"outputs":[]}]}