{"cells":[{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pylab as plt\nimport plotly.offline as py\nfrom plotly.graph_objs import *\nimport plotly.graph_objects as go\nfrom skimage import io\nimport cv2\nfrom skimage.color import rgb2lab, deltaE_cie76\nimport os\nfrom sklearn.cluster import KMeans\nfrom collections import Counter\nfrom plotly.subplots import make_subplots","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# NCAA March Madness is NEW to me\nYes, I am the captain of a women basketball team in my university society. But, I have never been to the US, or watch NCAA games much. So, this is realy a newbies notebook for me to learn from your comments, and enrich my knowledge! \n\n# Then, why this notebook?\nYou are here because you are ethusiatic about sports and sports analytics (with 3D) just like me! Hi talented Kagglers and people who are just looking for an interesting reading. I am going to explore :\n<br>\n<br>**1. Where to Shoot? **\n<br>    A basketball court-view to understand where the teams would have the greatest chance to score! Alternatively, where they may have the least chance haha. \nWe will cover both **3D & 2D** way of looking at the court.\n![shooting](https://media1.giphy.com/media/TEn16Gsw6q81Ruz4N0/200.webp?cid=790b761143f5660929d65dd8e4d8d013a2707ab4eac3d831&rid=200.webp)\n<br>    \n<br>**2. Where to Play?**\n<br>    There are more than 300 teams in the regular season, and only 68 teams enter into the tournament. Where do these teams coming from? "},{"metadata":{},"cell_type":"markdown","source":"As for now, we will look at the men's basketball first! I plan to create more visualization as I receive feedback from my kind readers! Thank you! "},{"metadata":{},"cell_type":"markdown","source":"# Where to Shoot? \nFind out the **best spot(s)** and the **worst spot(s)** for our **Final Four **in Season 2019!\n![Final Four](https://upload.wikimedia.org/wikipedia/en/thumb/7/77/2019_NCAA_Men%27s_Final_Four_logo.svg/440px-2019_NCAA_Men%27s_Final_Four_logo.svg.png)"},{"metadata":{},"cell_type":"markdown","source":"Skip this if you know how to play basketball: \n<br>  There are two kinds of regular shooting attempts, **2 points**(inside the blue line) & **3 points** (outside the blue line). The NCAA updated its 3 point line for the 2019-2020 Season.\n![court](https://og4sg2f1jmu2x9xay48pj5z1-wpengine.netdna-ssl.com/wp-content/uploads/2019/06/NCAA-Mens-and-Womens-Basketball-Court-Diagram-3-point-line-extended-2019.png)"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"M_Event_2019=pd.read_csv('../input/march-madness-analytics-2020/2020DataFiles/2020DataFiles/2020-Mens-Data/MEvents2019.csv')[['EventTeamID','X','Y','Area','EventType']]\nTeamIDmap=pd.read_csv('../input/march-madness-analytics-2020/2020DataFiles/2020DataFiles/2020-Mens-Data/MDataFiles_Stage1/MTeams.csv')[['TeamID','TeamName']]\nM_Event_2019=pd.merge(M_Event_2019,TeamIDmap,how='left', left_on=['EventTeamID'], right_on=['TeamID'])[['TeamName','X','Y','EventType']]\n\nmade3_2019_M=M_Event_2019[(M_Event_2019['EventType']=='made3')&(M_Event_2019['X']!=0)][['TeamName','X','Y']]\nmiss3_2019_M=M_Event_2019[(M_Event_2019['EventType']=='miss3')&(M_Event_2019['X']!=0)][['TeamName','X','Y']]\nmade3_2019_M['X']=made3_2019_M['X'].apply(lambda x: int((x-1)/10))\nmade3_2019_M['Y']=made3_2019_M['Y'].apply(lambda x: int((x-1)/20))\nmiss3_2019_M['X']=miss3_2019_M['X'].apply(lambda x: int((x-1)/10))\nmiss3_2019_M['Y']=miss3_2019_M['Y'].apply(lambda x: int((x-1)/20))\nmade3_team=made3_2019_M.groupby(['TeamName','X','Y']).size().rename('Made').reset_index()\nmiss3_team=miss3_2019_M.groupby(['TeamName','X','Y']).size().rename('Miss').reset_index()\nTeam_3=pd.merge(miss3_team,made3_team,on=['TeamName','X','Y'],how='outer').fillna(0)\nTeam_3['Made%']=Team_3['Made']/(Team_3['Made']+Team_3['Miss'])\nmean3_percentage=Team_3.groupby(['X','Y'])['Made%'].mean().reset_index()\nfor index,row in mean3_percentage.iterrows():\n  x=row['X']\n  y=row['Y']\n  percentage=row['Made%']\n  Team_3.loc[(Team_3['X']==x) & (Team_3['Y']==y),'mean']=percentage\nTeam_3['diff']=Team_3['Made%']-Team_3['mean']\nTeam_3['Total']=Team_3['Made']+Team_3['Miss']\n\nmade2_2019_M=M_Event_2019[(M_Event_2019['EventType']=='made2')&(M_Event_2019['X']!=0)][['TeamName','X','Y']]\nmiss2_2019_M=M_Event_2019[(M_Event_2019['EventType']=='miss2')&(M_Event_2019['X']!=0)][['TeamName','X','Y']]\nmade2_2019_M['X']=made2_2019_M['X'].apply(lambda x: int((x-1)/10))\nmade2_2019_M['Y']=made2_2019_M['Y'].apply(lambda x: int((x-1)/20))\nmiss2_2019_M['X']=miss2_2019_M['X'].apply(lambda x: int((x-1)/10))\nmiss2_2019_M['Y']=miss2_2019_M['Y'].apply(lambda x: int((x-1)/20))\nmade2_team=made2_2019_M.groupby(['TeamName','X','Y']).size().rename('Made').reset_index()\nmiss2_team=miss2_2019_M.groupby(['TeamName','X','Y']).size().rename('Miss').reset_index()\nTeam_2=pd.merge(miss2_team,made2_team,on=['TeamName','X','Y'],how='outer').fillna(0)\nTeam_2['Made%']=Team_2['Made']/(Team_2['Made']+Team_2['Miss'])\nmean_percentage=Team_2.groupby(['X','Y'])['Made%'].mean().reset_index()\nfor index,row in mean_percentage.iterrows():\n  x=row['X']\n  y=row['Y']\n  percentage=row['Made%']\n  Team_2.loc[(Team_2['X']==x) & (Team_2['Y']==y),'mean']=percentage\nTeam_2['diff']=Team_2['Made%']-Team_2['mean']\nTeam_2['Total']=Team_2['Made']+Team_2['Miss']","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Here we are going to look at how the Final Four perform at each spot,i.e. the relative shooting accuracy in respective to all teams!"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"img = cv2.imread('../input/ncaaoldcourt/basketball_court-2_(NCAAOld).png')\nmodified_image = cv2.resize(img, (100, 100))\nmodified_image = modified_image.reshape(modified_image.shape[0]*modified_image.shape[1], 3)\nclf = KMeans(n_clusters = 13)\nlabels = clf.fit_predict(modified_image)\ncenter_colors = clf.cluster_centers_\npl_color=[]\nfor i in range(13):\n  pl_color.append([i/13,'rgb('+str(center_colors[i][0])+','+str(center_colors[i][1])+','+str(center_colors[i][2])+')'])\nsurfcolor=np.reshape(labels,(100,100))\nsurfcolor=surfcolor/13","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"The **height/Z value** of the graph repsents the relative field goal percentage in respective to all teams' average shooting accuracy! \n<br>  Some interesting results: \n<br>\n<br> **Virginia Cavaliers**' Sweet Spot: **short corner**\n<br>\n<br> **Texas Tech Red Raiders**: not as accurate around **the free throw line** as other teams"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"def get_team_Z(teamname):\n  team=Team_all[Team_all['TeamName']==teamname]\n  threshold_total=np.quantile(team['Total'],0.25)\n  team=team[team['Total']>threshold_total]\n  team_all=np.zeros((100,100))\n  for i in list(set(team['X'])):\n    y=list(set(team[team['X']==i]['Y']))\n    for j in y:\n      team_all[j*20:j*20+20,i*10:i*10+10]=np.array([[team[(team['X']==i)&(team['Y']==j)]['diff'].values[0] for r in range(10)] for h in range (20)])\n  return team_all\n\nname=['Virginia','Texas Tech','Auburn','Michigan St']\nTeam_all=pd.concat([Team_2, Team_3], axis=0)\nfig = make_subplots(\n    subplot_titles=tuple(['<b>'+str(name[i])+'</b>'for i in range(4)]),\n    horizontal_spacing = 0.02,\n    vertical_spacing=0.02,\n    print_grid=False,\n    rows=2, cols=2,\n    specs=[[{'type': 'surface'}, {'type': 'surface'}],\n           [{'type': 'surface'}, {'type': 'surface'}]])\nsub_scene=dict(xaxis_visible=True,\n                      yaxis_visible=True, \n                      zaxis_visible=True,\n                      aspectmode='manual',\n                      aspectratio = dict(x=1, y=0.5319, z=0.4)\n                      )\nfor i in range(4):\n  fig.add_trace(go.Surface(z=get_team_Z(name[i]),\n                      x=np.linspace(0,940,100),\n                      y=np.linspace(0,500,100),\n                      surfacecolor=surfcolor,\n                      colorscale='Spectral',\n                      showscale =False\n                    ),\n                row=int(i/2+1), \n                col=int(i%2+1))\n\nfig.update_layout(\n    title='<b>Final Four relative shooting % in respective to all teams</b>', \n          width=800,\n          height=800,\n          autosize=False,\n          scene=sub_scene,\n          scene2=sub_scene,\n          scene3=sub_scene,\n          scene4=sub_scene\n                      )\nfig.add_layout_image(\n    dict(\n        source=\"https://upload.wikimedia.org/wikipedia/en/thumb/d/d1/Virginia_Cavaliers_sabre.svg/1200px-Virginia_Cavaliers_sabre.svg.png\",\n        xref=\"paper\", yref=\"paper\",\n         x=0, y=1,\n        sizex=0.15,sizey=0.15,\n    )\n)\nfig.add_layout_image(\n    dict(\n        source=\"https://upload.wikimedia.org/wikipedia/commons/thumb/4/4e/Texas_Tech_Athletics_logo.svg/1200px-Texas_Tech_Athletics_logo.svg.png\",\n        xref=\"paper\", yref=\"paper\",\n         x=0.8, y=1,\n        sizex=0.15,sizey=0.15,\n    )\n)\nfig.add_layout_image(\n    dict(\n        source=\"https://upload.wikimedia.org/wikipedia/commons/thumb/1/15/Auburn_Tigers_logo.svg/1200px-Auburn_Tigers_logo.svg.png\",\n        xref=\"paper\", yref=\"paper\",\n         x=0, y=0.2,\n        sizex=0.15,sizey=0.15,\n    )\n)\nfig.add_layout_image(\n    dict(\n        source=\"https://upload.wikimedia.org/wikipedia/en/thumb/a/a7/Michigan_State_Athletics_logo.svg/1200px-Michigan_State_Athletics_logo.svg.png\",\n        xref=\"paper\", yref=\"paper\",\n         x=0.8, y=0.2,\n        sizex=0.15,sizey=0.15,\n    )\n)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Let's take a 2D-look! \nFirst, we need to draw a 2D NCAA court"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"def create_ncaa_full_court():\n    trace1 = {\n      \"uid\": \"3608439e-d007-11e8-bf2c-f2189834773b\", \n      \"type\": \"scatter\", \n      \"x\": [47], \n      \"y\": [25],\n      \"marker\":{\"color\": \"rgba(0,0,0,0)\"},\n      \"showlegend\":False\n    }\n    data = Scatter(trace1)\n    layout = {\n        \"autosize\":False,\n        \"font\":dict(\n        family=\"Balto\",\n        size=18,\n        color=\"rgba(0,0,0,1)\"\n    ),\n      \"title\": \"NCAA Basketball Court\", \n      \"paper_bgcolor\":\"rgba(0,0,0,0)\",\n    \"plot_bgcolor\":\"rgba(0,0,0,0)\",\n      \"shapes\": [\n        {\n          \"x0\": 4, \n          \"x1\": 4, \n          \"y0\": 22, \n          \"y1\": 28, \n          \"line\": {\n            \"color\": \"rgba(0,0,0,1)\", \n            \"width\": 1\n          }, \n          \"type\": \"line\"\n        }, \n        {\n          \"x0\": 90, \n          \"x1\": 90, \n          \"y0\": 22, \n          \"y1\": 28, \n          \"line\": {\n            \"color\": \"rgba(0,0,0,1)\", \n            \"width\": 1\n          }, \n          \"type\": \"line\"\n        }, \n        {\n          \"x0\": 0, \n          \"x1\": 19, \n          \"y0\": 17, \n          \"y1\": 33, \n          \"line\": {\n            \"color\": \"rgba(0,0,0,1)\", \n            \"width\": 1\n          }, \n          \"type\": \"rect\"\n        }, \n        {\n          \"x0\": 0, \n          \"x1\": 19, \n          \"y0\": 19, \n          \"y1\": 31, \n          \"line\": {\n            \"color\": \"rgba(0,0,0,1)\", \n            \"width\": 1\n          }, \n          \"type\": \"rect\"\n        }, \n        {\n          \"x0\": 75, \n          \"x1\": 94, \n          \"y0\": 17, \n          \"y1\": 33, \n          \"line\": {\n            \"color\": \"rgba(0,0,0,1)\", \n            \"width\": 1\n          }, \n          \"type\": \"rect\"\n        }, \n        {\n          \"x0\": 75, \n          \"x1\": 94, \n          \"y0\": 19, \n          \"y1\": 31, \n          \"line\": {\n            \"color\": \"rgba(0,0,0,1)\", \n            \"width\": 1\n          }, \n          \"type\": \"rect\"\n        },  \n        {\n          \"x0\": 47, \n          \"x1\": 47, \n          \"y0\": 0, \n          \"y1\": 50, \n          \"line\": {\n            \"color\": \"rgba(0,0,0,1)\", \n            \"width\": 1\n          }, \n          \"type\": \"rect\"\n        }, \n        {\n          \"x0\": 6 ,\n          \"x1\": 4.5, \n          \"y0\": 25.75, \n          \"y1\": 24.25, \n          \"line\": {\n            \"color\": \"rgba(0,0,0,1)\", \n            \"width\": 1\n          }, \n          \"type\": \"circle\"\n        }, \n        {\n          \"x0\": 89.5, \n          \"x1\": 88, \n          \"y0\": 25.75, \n          \"y1\": 24.25, \n          \"line\": {\n            \"color\": \"rgba(0,0,0,1)\", \n            \"width\": 1\n          }, \n          \"type\": \"circle\"\n        }, \n        {\n          \"x0\": 25, \n          \"x1\": 13, \n          \"y0\": 31, \n          \"y1\": 19, \n          \"line\": {\n            \"color\": \"rgba(0,0,0,1)\", \n            \"width\": 1\n          }, \n          \"type\": \"circle\"\n        }, \n        {\n          \"x0\": 81, \n          \"x1\": 69, \n          \"y0\": 31, \n          \"y1\": 19, \n          \"line\": {\n            \"color\": \"rgba(0,0,0,1)\", \n            \"width\": 1\n          }, \n          \"type\": \"circle\"\n        }, \n        {\n          \"x0\": 53, \n          \"x1\": 41, \n          \"y0\": 31, \n          \"y1\": 19, \n          \"line\": {\n            \"color\": \"rgba(0,0,0,1)\", \n            \"width\": 1\n          }, \n          \"type\": \"circle\"\n        }, \n        {\n          \"x0\": 49, \n          \"x1\": 45, \n          \"y0\": 27, \n          \"y1\": 23, \n          \"line\": {\n            \"color\": \"rgba(0,0,0,1)\", \n            \"width\": 1\n          }, \n          \"type\": \"circle\"\n        }, \n        {\n          \"x0\": 68, \n          \"x1\": 109.5, \n          \"y0\": 4.25, \n          \"y1\": 45.75, \n          \"line\": {\n            \"color\": \"rgba(0,0,0,1)\", \n            \"width\": 1\n          }, \n          \"type\": \"circle\"\n        },\n            {\n          \"x0\": -15.5, \n          \"x1\": 26, \n          \"y0\": 4.25, \n          \"y1\": 45.75, \n          \"line\": {\n            \"color\": \"rgba(0,0,0,1)\", \n            \"width\": 1\n          }, \n          \"type\": \"circle\"\n        },\n          {\n          \"x0\": -15.5, \n          \"x1\": 0, \n          \"y0\": 50, \n          \"y1\": 0, \n         \"fillcolor\":\"white\",\n        \"line_color\":\"white\",\n          \"type\": \"rect\"\n        },\n          {\n          \"x0\": 110.25, \n          \"x1\": 94, \n          \"y0\": 50, \n          \"y1\": 0, \n         \"fillcolor\":\"white\",\n        \"line_color\":\"white\",\n          \"type\": \"rect\"\n        },\n            {\n          \"x0\": 0, \n          \"x1\": 94, \n          \"y0\": 0, \n          \"y1\": 50, \n          \"line\": {\n            \"color\": \"rgba(0,0,0,1)\", \n            \"width\": 1\n          }, \n          \"type\": \"rect\"\n        }, \n      ]\n    }\n    fig = Figure(data=data,layout=layout)\n    return fig\nempty=create_ncaa_full_court()\nempty","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"Made2_2019_M=M_Event_2019[(M_Event_2019['EventType']=='made2') & (M_Event_2019['X']!=0)]\nXY_Made2=Made2_2019_M.groupby(['X','Y']).size().rename('Count').reset_index()\nXY_Made2['X_corr']=XY_Made2['X']*0.94\nXY_Made2['Y_corr']=XY_Made2['Y']*0.5\nXY_Made2['log_Count']=np.log(XY_Made2['Count'])\nmade2_court=create_ncaa_full_court()\nmade2_court.add_scatter(x=XY_Made2['X_corr'], y=XY_Made2['Y_corr'],\n                    mode='markers',\n                    name='2 Points made',\n                    marker=dict(color=XY_Made2['log_Count'],\n                    colorscale=[[0.0, 'rgb(165,0,38)'], [0.1111111111111111, 'rgb(215,48,39)'], [0.2222222222222222, 'rgb(244,109,67)'],\n                    [0.3333333333333333, 'rgb(253,174,97)'], [0.4444444444444444, 'rgb(254,224,144)'], [0.5555555555555556, 'rgb(224,243,248)'],\n                    [0.6666666666666666, 'rgb(171,217,233)'],[0.7777777777777778, 'rgb(116,173,209)'], [0.8888888888888888, 'rgb(69,117,180)'],\n                    [1.0, 'rgb(49,54,149)']],\n                    reversescale=True,\n                    #colorscale='Burg', # one of plotly colorscales\n                    showscale=True,),\n                    showlegend=False,\n                    text=XY_Made2['log_Count'])\nmade2_court.update_layout({\"title\": \"<b>NCAA 2019 2-points shooting position </b>\",\"font\": {\n    \"family\": 'Courier New, monospace',\n    \"size\":18,\n  }})","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Here, the colorscale refers to log(# of times of shooting)"},{"metadata":{},"cell_type":"markdown","source":"What about 3-points?"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"Miss3_2019_M=M_Event_2019[(M_Event_2019['EventType']=='miss3') & (M_Event_2019['X']!=0)]\nXY_Miss3=Miss3_2019_M.groupby(['X','Y']).size().rename('Count').reset_index()\nMade3_2019_M=M_Event_2019[(M_Event_2019['EventType']=='made3') & (M_Event_2019['X']!=0)]\nXY_Made3=Made3_2019_M.groupby(['X','Y']).size().rename('Count').reset_index()\nXY_Miss3['X_corr']=XY_Miss3['X']*0.94\nXY_Miss3['Y_corr']=XY_Miss3['Y']*0.5\nXY_Made3['X_corr']=XY_Made3['X']*0.94\nXY_Made3['Y_corr']=XY_Made3['Y']*0.5\nXY_Miss3=XY_Miss3.rename(columns={'Count':'Miss'})\nXY_Made3=XY_Made3.rename(columns={'Count':'Made'})\nXY_3=pd.merge(XY_Miss3,XY_Made3,on=['X_corr','Y_corr'],how='outer').fillna(0)\nXY_3['Made%']=XY_3['Made']/(XY_3['Made']+XY_3['Miss'])\nXY_3['Total']=XY_3['Made']+XY_3['Miss']\nXY_3=XY_3[XY_3['Total']>=3]\nThreepts_court=create_ncaa_full_court()\nThreepts_court.add_scatter(x=XY_3['X_corr'], y=XY_3['Y_corr'],\n                    mode='markers',\n                    name='3 Points accuracy',\n                    marker=dict(symbol=\"hexagon\",\n                        color=np.log(XY_3['Made']),\n                    colorscale=[[0.0, 'rgb(165,0,38)'], [0.1111111111111111, 'rgb(215,48,39)'], [0.2222222222222222, 'rgb(244,109,67)'],\n                    [0.3333333333333333, 'rgb(253,174,97)'], [0.4444444444444444, 'rgb(254,224,144)'], [0.5555555555555556, 'rgb(224,243,248)'],\n                    [0.6666666666666666, 'rgb(171,217,233)'],[0.7777777777777778, 'rgb(116,173,209)'], [0.8888888888888888, 'rgb(69,117,180)'],\n                    [1.0, 'rgb(49,54,149)']],\n                    reversescale=True,\n                    #colorscale='Burg', # one of plotly colorscales\n                    showscale=True,),\n                    showlegend=False,\n                    text=XY_3['Made'])\nThreepts_court.update_layout({\"font\": {\n    \"family\": 'Courier New, monospace',\n    \"size\":18,\n  },\"title\": \"<b>NCAA 2019 3-points shooting position</b>\"})","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Let'scombine - we have both 2-points & 3-points:"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"Threepts_court.add_scatter(x=XY_Made2['X_corr'], y=XY_Made2['Y_corr'],\n                    mode='markers',\n                    name='2 Points made',\n                    marker=dict(color=XY_Made2['log_Count'],\n                    colorscale=[[0.0, 'rgb(165,0,38)'], [0.1111111111111111, 'rgb(215,48,39)'], [0.2222222222222222, 'rgb(244,109,67)'],\n                    [0.3333333333333333, 'rgb(253,174,97)'], [0.4444444444444444, 'rgb(254,224,144)'], [0.5555555555555556, 'rgb(224,243,248)'],\n                    [0.6666666666666666, 'rgb(171,217,233)'],[0.7777777777777778, 'rgb(116,173,209)'], [0.8888888888888888, 'rgb(69,117,180)'],\n                    [1.0, 'rgb(49,54,149)']],\n                    reversescale=True,\n                    #colorscale='Burg', # one of plotly colorscales\n                    ),\n                    showlegend=False,\n                    text=XY_Made2['log_Count'])\nThreepts_court.update_layout({\"title\": \"<b>NCAA 2019 2-points & 3-points</b>\",\"font\": {\n    \"family\": 'Courier New, monospace',\n    \"size\":18,\n  }})","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Besides **shooting position**, we are also interesting in **the accuracy at the shooting position**\nAs 3-points are relatively hard to obtain, we **add more weights** on the color to represent the difficulty beyond the 3-point line"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"Miss2_2019_M=M_Event_2019[(M_Event_2019['EventType']=='miss2') & (M_Event_2019['X']!=0)]\nXY_Miss2=Miss2_2019_M.groupby(['X','Y']).size().rename('Count').reset_index()\nXY_Miss2['X_corr']=XY_Miss2['X']*0.94\nXY_Miss2['Y_corr']=XY_Miss2['Y']*0.5\nXY_Miss2=XY_Miss2.rename(columns={'Count':'Miss'})\nXY_Made2=XY_Made2.rename(columns={'Count':'Made'})\nXY_2=pd.merge(XY_Miss2,XY_Made2,on=['X_corr','Y_corr'],how='outer').fillna(0)\nXY_2['Made%']=XY_2['Made']/(XY_2['Made']+XY_2['Miss'])\nXY_2=XY_2[XY_2['Made']>=2]\nXY_2=XY_2[XY_2['Miss']>=4]\nTwopts_court=create_ncaa_full_court()\nTwopts_court.add_scatter(x=XY_2['X_corr'], y=XY_2['Y_corr'],\n                    mode='markers',\n                    name='2 Points accuracy',\n                    marker=dict(color=XY_2['Made%'],\n                    colorscale=[[0.0, 'rgb(165,0,38)'], [0.1111, 'rgb(215,48,39)'], [0.22222, 'rgb(244,109,67)'],\n                    [0.333, 'rgb(253,174,97)'], [0.4444, 'rgb(254,224,144)'], [0.5555, 'rgb(224,243,248)'],\n                    [0.6666, 'rgb(171,217,233)'],[0.7777, 'rgb(116,173,209)'], [0.8888, 'rgb(69,117,180)'],\n                    [1.0, 'rgb(49,54,149)']],\n                    reversescale=True,\n                    #colorscale='Burg', # one of plotly colorscales\n                    ),\n                    showlegend=False,\n                    text=XY_2['Made%'])\nTwopts_court.add_scatter(x=XY_3['X_corr'], y=XY_3['Y_corr'],\n                    mode='markers',\n                    name='3 Points accuracy',\n                    marker=dict(symbol=\"hexagon\",\n                        color=XY_3['Made%'],\n                    colorscale=[[0.0, 'rgb(165,0,38)'], [1/7, 'rgb(215,48,39)'], [2/7, 'rgb(244,109,67)'],\n                    [3/7, 'rgb(253,174,97)'], [4/7, 'rgb(254,224,144)'],[5/7, 'rgb(224,243,248)'],[6/7, 'rgb(171,217,233)'],[1, 'rgb(116,173,209)']],\n                    reversescale=True,\n                    #colorscale='Burg', # one of plotly colorscales\n                    showscale=True,),\n                    showlegend=False,\n                    text=XY_3['Made%'])\nTwopts_court.update_layout({\"font\": {\n    \"family\": 'Courier New, monospace',\n    \"size\":18,\n  },\"title\": \"<b>NCAA 2019 Field Goals </b>\"})","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Where to Play\n\nAnother question arises is that, if you are a fan, where you should go for those exciting games? Does the number of teams from each state vary from year to year? "},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"Cities=pd.read_csv('../input/march-madness-analytics-2020/2020DataFiles/2020DataFiles/2020-Mens-Data/MDataFiles_Stage1/Cities.csv')\nCities_Game=pd.read_csv('../input/march-madness-analytics-2020/2020DataFiles/2020DataFiles/2020-Mens-Data/MDataFiles_Stage1/MGameCities.csv')\nGame_count=pd.merge(Cities_Game,Cities).groupby(['Season','State']).size().rename('Game_count').reset_index()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"CompactResults=pd.read_csv('../input/march-madness-analytics-2020/2020DataFiles/2020DataFiles/2020-Mens-Data/MDataFiles_Stage1/MRegularSeasonCompactResults.csv')\nhome_game=pd.merge(CompactResults,Cities_Game)[['Season','WTeamID','LTeamID','WLoc','CityID']]\nhome_game=home_game[(home_game['WLoc']=='H') |(home_game['WLoc']=='A')]\nhome_game['home_team']=home_game.apply(lambda row: row['WTeamID'] if row['WLoc']=='H' else row['LTeamID'],axis=1)\nseason_team_city=home_game.groupby(['Season','home_team','CityID']).size().rename('games').reset_index()\nteam_city_state=pd.merge(season_team_city,Cities)\nteam_state=team_city_state.groupby(['Season','State']).size().rename('NumberofTeams').reset_index()\n# Create figure\nfig = go.Figure()\n\n# Add traces, one for each slider step\nfor step in np.arange(2010, 2020, 1):\n    fig.add_trace(\n      go.Choropleth(\n    locations=team_state[team_state['Season']==step]['State'], # Spatial coordinates\n    z = team_state[team_state['Season']==step]['NumberofTeams'].astype(float), # Data to be color-coded\n    locationmode = 'USA-states', # set of locations match entries in `locations`\n    colorscale=[[0.0, 'rgb(165,0,38)'], [0.1111111111111111, 'rgb(215,48,39)'], [0.2222222222222222, 'rgb(244,109,67)'],\n        [0.3333333333333333, 'rgb(253,174,97)'], [0.4444444444444444, 'rgb(254,224,144)'], [0.5555555555555556, 'rgb(224,243,248)'],\n        [0.6666666666666666, 'rgb(171,217,233)'],[0.7777777777777778, 'rgb(116,173,209)'], [0.8888888888888888, 'rgb(69,117,180)'],\n        [1.0, 'rgb(49,54,149)']],\n    reversescale=True,\n    colorbar_title = \"#Teams\",\n    marker_line_color='white',\n    text = team_state['State'],\n    hovertemplate = '<b>State</b>: <b>%{text}</b>'+\n    '<br><b>#Teams </b>: %{z}<br>',\n    zmin=0,\n    zmax=25\n))\n\n# Make 10th trace visible\n#fig.data[9].visible = True\n\n# Create and add slider\nsteps = []\nfor i in range(len(fig.data)):\n    step = dict(\n        method=\"restyle\",\n        args=[\"visible\", [False] * len(fig.data)],\n        label='Season {}'.format(i + 2010)\n    )\n    step[\"args\"][1][i] = True  # Toggle i'th trace to \"visible\"\n    steps.append(step)\n\nsliders = [dict(\n    active=10,\n    currentvalue={\"prefix\": \"Selected Season: \"},\n    pad={\"t\": 10},\n    steps=steps\n)]\n\nfig.update_layout(\n    title_text='<b>2011-2019 NCAA Regular Season #Teams by State</b><br>(Hover for breakdown)',\n    sliders=sliders,\n    geo_scope='usa'\n)\n\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Use the slider to choose the season and see the trend! "},{"metadata":{"trusted":true,"collapsed":true,"_kg_hide-input":true},"cell_type":"code","source":"Tourney_seeds=pd.read_csv('../input/march-madness-analytics-2020/2020DataFiles/2020DataFiles/2020-Mens-Data/MDataFiles_Stage1/MNCAATourneySeeds.csv')\nTeam_name=pd.read_csv('../input/march-madness-analytics-2020/2020DataFiles/2020DataFiles/2020-Mens-Data/MDataFiles_Stage1/MTeams.csv')[['TeamID','TeamName']]\nteam_tourney=pd.merge(Tourney_seeds.groupby(['Season','TeamID']).size().reset_index()[['Season','TeamID']],team_city_state.rename(columns={'home_team':'TeamID'}).drop_duplicates(subset=['TeamID','Season','State']))[['Season','TeamID','City','State']]\nTeam_name_state=pd.merge(team_tourney.groupby(['Season','State','TeamID']).size().reset_index()[['Season','State','TeamID']],Team_name[['TeamID','TeamName']])\nState_all_team=Team_name_state.groupby(['Season','State'],as_index=False)[['TeamName']].aggregate(lambda x: set(x))\nState_all_team['#Teams']=State_all_team.apply(lambda row: len(row['TeamName']),axis=1)\nState_all_team['Text']='<b>Teams</b>:'+State_all_team['TeamName'].apply(lambda x: '<br>'.join(str(s) for s in x))\nall_states=State_all_team['State'].unique().tolist()\nfor i in range(10):\n  season=2010+i\n  season_state=State_all_team[State_all_team['Season']==season]['State'].unique().tolist()\n  not_season_state=set(all_states)-set(season_state)\n  not_in=len(not_season_state)\n  extra_state=pd.DataFrame()\n  extra_state['State']=list(not_season_state)\n  extra_state['Season']=[season for s in range(not_in)]\n  extra_state['#Teams']=[0 for s in range(not_in)]\n  extra_state['TeamName']=['None' for s in range(not_in)]\n  extra_state['Text']='None'\n  State_all_team=pd.concat([State_all_team,extra_state])\nState_all_team=State_all_team.sort_values(by=['Season','State'])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"How about teams that enter into the NCAA Tourney? What were those teams? "},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"# Create figure\nfig = go.Figure()\n\n# Add traces, one for each slider step\nfor step in np.arange(2010, 2020, 1):\n    fig.add_trace(\n      go.Choropleth(\n    locations=State_all_team[State_all_team['Season']==step]['State'], # Spatial coordinates\n    z = State_all_team[State_all_team['Season']==step]['#Teams'].astype(float), # Data to be color-coded\n    locationmode = 'USA-states', # set of locations match entries in `locations`\n    colorscale=[[0.0, 'rgb(165,0,38)'], [0.1111111111111111, 'rgb(215,48,39)'], [0.2222222222222222, 'rgb(244,109,67)'],\n        [0.3333333333333333, 'rgb(253,174,97)'], [0.4444444444444444, 'rgb(254,224,144)'], [0.5555555555555556, 'rgb(224,243,248)'],\n        [0.6666666666666666, 'rgb(171,217,233)'],[0.7777777777777778, 'rgb(116,173,209)'], [0.8888888888888888, 'rgb(69,117,180)'],\n        [1.0, 'rgb(49,54,149)']],\n    reversescale=True,\n    colorbar_title = \"#Teams\",\n    marker_line_color='white',\n    text = State_all_team[State_all_team['Season']==step]['Text'],\n    zmin=0,\n    zmax=7\n))\n\n# Make 10th trace visible\n#fig.data[9].visible = True\n\n# Create and add slider\nsteps = []\nfor i in range(len(fig.data)):\n    step = dict(\n        method=\"restyle\",\n        args=[\"visible\", [False] * len(fig.data)],\n        label='Season {}'.format(i + 2010)\n    )\n    step[\"args\"][1][i] = True  # Toggle i'th trace to \"visible\"\n    steps.append(step)\n\nsliders = [dict(\n    active=10,\n    currentvalue={\"prefix\": \"Selected Season: \"},\n    pad={\"t\": 10},\n    steps=steps\n)]\n\nfig.update_layout(\n    title_text='<b>2011-2019 NCAA Tourney #Teams by State</b><br>(Hover for breakdown)',\n    sliders=sliders,\n    geo_scope='usa'\n)\n\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<img src=\"https://media3.giphy.com/media/SVNj1b7mnrtymluuKC/giphy.webp?cid=790b7611afdec6cb40fcd2d6708822a3a93c7b7d030e10d9&rid=giphy.webp\" width=\"00\">\n<br>\nWow, Texas is definitely worth going! "},{"metadata":{},"cell_type":"markdown","source":"Here's all work I have explored so far. Your feedback and comments is truly welcomed! \nFeel free to point out if there's any thing I can correct/improve/elaborate. I will continue to update this notebook in the coming days\n![](https://media3.giphy.com/media/Z54VPIMUNTnyg/200.webp?cid=790b7611c0af5ae94be0ea5baa5fbaca08e04b33c213a2e0&rid=200.webp)"}],"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":4,"nbformat_minor":4}