{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"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 in \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 \"../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# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"library(dplyr)\nlibrary(ggplot2)\nlibrary(ggthemes)\ndata_injury <- read.csv('../input/nfl-playing-surface-analytics/InjuryRecord.csv')\ndata_PlayList <- read.csv('../input/nfl-playing-surface-analytics/PlayList.csv')\ndata_PlayTrack <- read.csv('../input/nfl-playing-surface-analytics/PlayerTrackData.csv')\ndata_PlayTrack%>% head\ndata_injury%>%head\ndata_PlayList%>%head","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Afficher un graphe avec les valeurs manquantes vs les valeurs observees****"},{"metadata":{"trusted":true},"cell_type":"code","source":"library(Amelia)\nmissmap(data_injury,main=\"Missing valeus vs observed _InjuryRecord_\")\nmissmap(data_PlayList,main=\"Missing valeus vs observed _PlayList_\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# libraries\nlibrary(tidyverse)\nlibrary(lubridate)\nlibrary(scales)\nlibrary(ggridges)\n\n# set up plotting theme\ntheme_jason <- function(legend_pos=\"top\", base_size=12, font=NA){\n  \n  # come up with some default text details\n  txt <- element_text(size = base_size+3, colour = \"black\", face = \"plain\")\n  bold_txt <- element_text(size = base_size+3, colour = \"black\", face = \"bold\")\n  \n  # use the theme_minimal() theme as a baseline\n  theme_minimal(base_size = base_size, base_family = font)+\n    theme(text = txt,\n          # axis title and text\n          axis.title.x = element_text(size = 15, hjust = 1),\n          axis.title.y = element_text(size = 15, hjust = 1),\n          # gridlines on plot\n          panel.grid.major = element_line(linetype = 2),\n          panel.grid.minor = element_line(linetype = 2),\n          # title and subtitle text\n          plot.title = element_text(size = 18, colour = \"grey25\", face = \"bold\"),\n          plot.subtitle = element_text(size = 16, colour = \"grey44\"),\n\n          ###### clean up!\n          legend.key = element_blank(),\n          # the strip.* arguments are for faceted plots\n          strip.background = element_blank(),\n          strip.text = element_text(face = \"bold\", size = 13, colour = \"grey35\")) +\n\n    #----- AXIS -----#\n    theme(\n      #### remove Tick marks\n      axis.ticks=element_blank(),\n\n      ### legend depends on argument in function and no title\n      legend.position = legend_pos,\n      legend.title = element_blank(),\n      legend.background = element_rect(fill = NULL, size = 0.5,linetype = 2)\n\n    )\n}\n\n\nplot_cols <- c(\"#498972\", \"#3E8193\", \"#BC6E2E\", \"#A09D3C\", \"#E06E77\", \"#7589BC\", \"#A57BAF\", \"#4D4D4D\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_PlayList %>% \n  count(StadiumType) %>% \n  rename(Count = n) %>% \n  mutate(Count = comma(Count)) %>% \n  kableExtra::kable(format = \"html\", escape = F) %>%\n  kableExtra::kable_styling(\"striped\", full_width = F) %>% \n  kableExtra::scroll_box(height = \"500px\") %>%\n  kableExtra::kable_styling(fixed_thead = T)\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_injury %>%   \n  count(BodyPart)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_injury %>%   \n  count(BodyPart) %>%  \n  ggplot(aes(x= reorder(BodyPart,n), y= n)) +\n  geom_col(fill = plot_cols[1], colour = plot_cols[1], alpha = 0.6) +\n  labs(x= \"Body Part\", y= \"Num Injuries\") +\n  ggtitle(\"NOT ALL NFL BODY PARTS ARE CREATED EQUAL\", subtitle = \"86% of the injury records made up by knees and ankles\") +\n  coord_flip() +\n  theme_jason()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\np1 <- data_PlayList %>% \n  distinct(GameID, FieldType) %>% \n  count(FieldType) %>% \n  ggplot(aes(x= FieldType, y= n)) +\n  geom_col(fill = plot_cols[3], colour = plot_cols[3], alpha = 0.6) +\n  labs(x= \"Surface\", y= \"Games Played\") +\n  ggtitle(\"MORE GAMES PLAYED ON NATURAL TURF\", subtitle = \"58% of games in our data played on Natural Turf\") +\n  scale_y_continuous(labels = comma) +\n  coord_flip() +\n  theme_jason()\n\np2 <-data_injury %>% \n  count(Surface) %>% \n  ggplot(aes(x= Surface, y= n)) +\n  geom_col(fill = plot_cols[1], colour = plot_cols[1], alpha = 0.6) +\n  labs(x= \"Surface\", y= \"Num Injuries\") +\n  ggtitle(\"SLIGHT DIFFERENCE IN SURFACE OCCURRENCES\", subtitle = \"Synthetic surfaces have slightly more injuries in absolute terms\") +\n  coord_flip() +\n  theme_jason()\n\n\ngridExtra::grid.arrange(p1, p2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# create a variable to indicate whether an injury occurred \ndata_PlayList <-data_PlayList %>% \n  mutate(IsInjured = GameID %in% data_injury$GameID)\n\n\n# play_list %>% \n#   distinct(GameID, FieldType, IsInjured) %>% \n#   count(IsInjured) %>% \n#   mutate(prop = n/sum(n))\n\ndata_PlayList %>% \n  distinct(GameID, FieldType, IsInjured) %>% \n  group_by(FieldType, IsInjured) %>% \n  summarise(n = n()) %>% \n  mutate(perc_injured = n / sum(n)) %>% \n  filter(IsInjured == TRUE) %>% \n  ggplot(aes(x= FieldType, y= perc_injured)) +\n  geom_col(alpha = 0.6, fill = plot_cols[1], colour = plot_cols[1]) +\n  geom_text(aes(label = percent(perc_injured)), vjust=1, size = 7, colour = plot_cols[8]) +\n  geom_hline(yintercept = 0.0182, linetype = 2, colour = plot_cols[3]) +\n  annotate(geom = \"text\", x=0.8, y= 0.0192, label = \"Injuries occur on\\n1.8% of all plays\", colour = plot_cols[3], size = 5) +\n  ggtitle(\"MORE LIKELY TO BE INJURED ON SYNTHETIC SURFACES\", subtitle = \"Of over 5,700 plays analysed, injuries\\noccured more frequently on Synthetic\") +\n  theme_jason() +\n  theme(axis.title.y = element_blank(), axis.text.y = element_blank())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_injury %>% \n  ggplot(aes(x=BodyPart, fill = Surface, colour = Surface)) +\n  geom_bar(stat = \"count\", position = \"fill\", alpha = 0.6) +\n  scale_fill_manual(values = plot_cols[c(2,3)]) +\n  scale_colour_manual(values = plot_cols[c(2,3)]) +\n  scale_y_continuous(labels = percent) +\n  ggtitle(\"SURFACE AND BODY TYPE SHOW SOME RELATIONSHIP\", subtitle = \"60% of ankle injuries occur on Synthetic, while\\nknee injuries occur with identical frequency on both surfaces\") +\n  theme_jason() +\n  theme(axis.title.y = element_blank())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# create a variable to indicate the severity of the injury (time missed)\ndata_injury <- data_injury %>% \n  mutate(severity = ifelse(DM_M42 == 1, \"42\", \n                           ifelse(DM_M42 == 0 & DM_M28 == 1, \"28\",\n                                  ifelse(DM_M42 == 0 & DM_M28 == 0 & DM_M7 == 1, \"7\", \"1\"))))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_injury%>% \n  # count(Surface, DM_M42) %>% \n  ggplot(aes(x=BodyPart, fill = factor(severity, levels = c(\"42\", \"28\", \"7\", \"1\")), colour = factor(severity, levels = c(\"42\", \"28\", \"7\", \"1\")))) +\n  geom_bar(stat = \"count\", position = \"fill\", alpha = 0.6) +\n  scale_fill_manual(values = plot_cols, name = \"Severity\") +\n  scale_colour_manual(values = plot_cols, guide = \"none\") +\n  scale_y_continuous(labels = percent) +\n  ggtitle(\"SOME DIFFERENCES BETWEEN BODY PART AND SEVERITY\", subtitle = \"Foot injuries generally longer recovery times\") +\n  theme_jason() +\n  theme(axis.title.y = element_blank())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_injury %>% \n  # count(Surface, DM_M42) %>% \n  ggplot(aes(x=Surface, fill = factor(severity, levels = c(\"42\", \"28\", \"7\", \"1\")), colour = factor(severity, levels = c(\"42\", \"28\", \"7\", \"1\")))) +\n  geom_bar(stat = \"count\", position = \"fill\", alpha = 0.6) +\n  scale_fill_manual(values = plot_cols, name = \"Severity\") +\n  scale_colour_manual(values = plot_cols, guide = \"none\") +\n  scale_y_continuous(labels = percent) +\n  ggtitle(\"MINIMAL DIFFERENCES IN SEVERITY BASED ON SURFACE\", subtitle = \"The time missed because of injury doesn't really differ\\nbetween playing surfaces\") +\n  theme_jason() +\n  theme(axis.title.y = element_blank())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# because there are some injuries without a playID, I will derive the player's position from the play_list df,\n# then join on to injury_record\na <- data_PlayList %>% filter(!is.na(Position), Position != \"Missing Data\") %>% distinct(PlayerKey, Position)\n\n# join to data\ndata_injury <- data_injury %>% left_join(a, by = \"PlayerKey\")\n\n# remove the duplicate occurrence of where players have multiple positions\ndata_injury <- data_injury %>% \n  # mutate(Position = ifelse(is.na(Position), CleanPosition, Position)) %>% \n  distinct(PlayKey, GameID, BodyPart, .keep_all = T) \n\n\n# join variables that can be joined at the game level:\ndata_injury <- data_injury %>% \n  left_join(data_PlayList %>% select(GameID, StadiumType, FieldType, Temperature, Weather), by = \"GameID\") %>% \n  distinct(.keep_all = T)\n\n\n# join per play variables\ndata_injury <- data_injury  %>% \n  left_join(data_PlayList %>% select(PlayKey, PlayerDay, PlayerGame, PlayType, PlayerGamePlay), by = \"PlayKey\")\n\n# fill in missing game number variable where there was no playID in the injury report\ndata_injury  <- data_injury  %>% \n  mutate(PlayerGame = ifelse(is.na(PlayerGame), as.numeric(str_extract(GameID, \"[^-]*$\")), PlayerGame))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"p1 <- data_injury %>% \n  count(Position) %>% \n  ggplot(aes(x= reorder(Position,n), y= n)) +\n  geom_col(fill = plot_cols[1], colour = plot_cols[1], alpha = 0.6) +\n  ggtitle(\"SOME PLAYERS INJURED MORE OFTEN THAN OTHERS\", subtitle = \"Wide Receivers and Outside Linebackers\\nthe most frequently injured\") +\n  labs(x= \"Position on Play\", y= \"Injury Count\") +\n  coord_flip() +\n  theme_jason()\n  \np2 <- data_injury %>% \n  count(Position, BodyPart) %>% \n  ggplot(aes(x= reorder(Position,n), y= n, fill = BodyPart, colour = BodyPart)) +\n  geom_bar(stat = \"identity\", position = \"fill\", alpha = 0.6) +\n  scale_fill_manual(values = plot_cols, name = \"Body Part\") +\n  scale_colour_manual(values = plot_cols, guide = \"none\") +\n  scale_y_continuous(labels = percent) +\n  ggtitle(\"OLBs AND ILBs INJURE KNEES, MLBs INJURE ANKLES?\", subtitle = \"Body part injured seems to differ\\nbased on player's position on the play\") +\n  labs(x= \"Position on Play\", y= \"Injury Proportion\") +\n  coord_flip() +\n  theme_jason()\n\ngridExtra::grid.arrange(p1, p2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_PlayList %>% \n  filter(!PlayType %in% c(\"\", \"0\")) %>% \n  group_by(PlayType, FieldType, IsInjured) %>% \n  summarise(n_Plays = n_distinct(PlayKey)) %>% \n  mutate(proportion_plays = round(n_Plays / sum(n_Plays), 2)) %>% group_by(PlayType, FieldType) %>% mutate(total_plays = sum(n_Plays)) %>% ungroup() %>%\n  filter(IsInjured == TRUE) %>%\n  ggplot(aes(x= reorder(PlayType, total_plays), y= total_plays)) +\n  geom_col(fill = plot_cols[3], colour = plot_cols[3], alpha = 0.6) +\n  geom_text(aes(label = percent(proportion_plays)), hjust=-0, size =5, colour = plot_cols[8]) +\n  scale_y_continuous(labels = comma, name = \"Total Plays\") +\n  ggtitle(\"SPECIAL TEAMS PLAYS ON SYNTHETIC MORE SUSCEPTIBLE TO INJURY\", subtitle = \"Greater proportion of plays involving punts and PATs\\nend in injury on Synthetic\") +\n  coord_flip() +\n  theme_jason() +\n  theme(axis.title.y = element_blank()) +\n  facet_wrap(~ FieldType)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_injury %>% \n  ggplot(aes(x= FieldType, y= PlayerGamePlay, fill = FieldType, colour = FieldType)) +\n  geom_boxplot(alpha = 0.5) +\n  scale_fill_manual(values = plot_cols, guide = \"none\") +\n  scale_colour_manual(values = plot_cols, guide = \"none\") +\n  ggtitle(\"INJURIES OCCUR EARLIER ON NATURAL SURFACES\", subtitle = \"28 records not included as exact play\\nwhere injury occurred is unknown\") +\n  labs(x= \"Field Type\", y= \"Game Play\") +\n  theme_jason()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"p1 <- data_injury%>% \n  group_by(PlayerGame) %>% summarise(num_players = n_distinct(PlayerKey)) %>% \n  ggplot(aes(x=PlayerGame, y=num_players)) +\n  geom_line(colour = plot_cols[1], size = 1) +\n  geom_point(colour = plot_cols[1], size = 3) +\n  labs(x= \"Game Number\", y= \"Number Injuries\") +\n  ggtitle(\"NUMBER OF INJURIES DECREASING THROUGH GAMES\", subtitle = \"Week 3 has the most injuries (n=9)\") +\n  theme_jason()\n\n\np2 <- data_PlayList %>% \n  group_by(PlayerGame) %>% summarise(num_players = n_distinct(PlayerKey)) %>% \n  ggplot(aes(x=PlayerGame, y=num_players)) +\n  geom_line(colour = plot_cols[3], size = 1) +\n  geom_point(colour = plot_cols[3], size = 3) +\n  labs(x= \"Game Number\", y= \"Number Players\") +\n  ggtitle(\"NUMBER OF PLAYERS ALSO DECREASING\", subtitle = \"Need to see whether the proportion is increasing or decreasing\") +\n  theme_jason()\n\ngridExtra::grid.arrange(p1, p2, ncol = 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_injury %>% \n  group_by(PlayerGame) %>% summarise(num_injured = n_distinct(PlayerKey)) %>% ungroup() %>% \n  left_join( data_PlayList %>% group_by(PlayerGame) %>% summarise(num_players = n_distinct(PlayerKey)) %>% ungroup(), by = \"PlayerGame\") %>% \n  mutate(prop_injured = num_injured / num_players) %>% \n  ggplot(aes(x=PlayerGame, y=prop_injured)) +\n  geom_line(colour = plot_cols[2], size = 1) +\n  geom_point(colour = plot_cols[2], size = 3) +\n  labs(x= \"Game Number\", y= \"Injury Rate\") +\n  scale_y_continuous(labels = percent) +\n  ggtitle(\"PLAYERS MORE LIKELY INJURED BY THE 8th GAME\", subtitle = \"The injury rate peaks at week 3 to 3.6%\") +\n  theme_jason()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_PlayList %>% \n  filter(StadiumType %in% c(\"dome_open\", \"indoor open\", \"outdoor\")) %>% \n  filter(Temperature != -999) %>% \n  distinct(GameID, Temperature, IsInjured) %>% \n  ggplot(aes(y= Temperature, x = IsInjured, fill = IsInjured, colour = IsInjured)) +\n  geom_boxplot(alpha = 0.5) +\n  scale_fill_manual(values = plot_cols, guide = \"none\") +\n  scale_colour_manual(values = plot_cols, guide = \"none\") +\n  labs(x= \"Player Injured?\") +\n  ggtitle(\"TEMPERATURE ISN'T A BIG FACTOR\", subtitle = \"While injuries tend to occur in slightly higher\\ntemperatures, doesn't look significant\") +\n  coord_flip() +\n  theme_jason()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_PlayList %>% \n  filter(Weather != \"indoors\") %>% \n  group_by(Weather, IsInjured) %>% \n  summarise(n_Plays = n_distinct(PlayKey)) %>% \n  mutate(proportion_plays = round(n_Plays / sum(n_Plays), 2)) %>% \n  filter(IsInjured == TRUE) %>%\n  ggplot(aes(x= reorder(Weather, n_Plays), y= proportion_plays, fill = IsInjured, colour = IsInjured)) +\n  geom_col(alpha = 0.6) +\n  scale_fill_manual(values = plot_cols, guide = \"none\") +\n  scale_colour_manual(values = plot_cols, guide = \"none\") +\n  geom_text(aes(label = percent(proportion_plays)), hjust= 1, size =5, colour = plot_cols[8]) +\n  scale_y_continuous(labels = comma, name = \"% Plays\") +\n  ggtitle(\"INJURIES MORE LIKELY TO OCCUR IN THE RAIN\", subtitle = \"No injuries in the snow is a surprise though\") +\n  labs(caption = \"*Indoor stadiums excluded\") +\n  coord_flip() +\n theme_jason() +\n  theme(axis.title.y = element_blank(), axis.text.x = element_blank(), plot.caption = element_text(colour = \"darkgrey\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_PlayList %>% \n  group_by(StadiumType, IsInjured) %>% \n  summarise(n_Plays = n_distinct(PlayKey)) %>% \n  mutate(proportion_plays = round(n_Plays / sum(n_Plays), 2)) %>% \n  filter(IsInjured == TRUE) %>%\n  ggplot(aes(x= reorder(StadiumType, n_Plays), y= proportion_plays, fill = IsInjured, colour = IsInjured)) +\n  geom_col(alpha = 0.6) +\n  scale_fill_manual(values = plot_cols, guide = \"none\") +\n  scale_colour_manual(values = plot_cols, guide = \"none\") +\n  geom_text(aes(label = percent(proportion_plays)), hjust= 1, size =5, colour = plot_cols[8]) +\n  scale_y_continuous(labels = comma, name = \"% Plays\") +\n  ggtitle(\"WHY ARE WE OPENING THE ROOF?!\", subtitle = \"Injuries are more likely to occur in indoor stadiums with the roof open\") +\n  coord_flip() +\n  theme_jason() +\n  theme(axis.title.y = element_blank(), axis.text.x = element_blank())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_PlayList %>% \n  group_by(StadiumType, FieldType, IsInjured) %>% \n  summarise(n_Plays = n_distinct(PlayKey)) %>% \n  mutate(proportion_plays = round(n_Plays / sum(n_Plays), 2)) %>% \n  filter(IsInjured == TRUE) %>%\n  ggplot(aes(x= reorder(StadiumType, n_Plays), y= proportion_plays, fill = FieldType, colour = FieldType)) +\n  geom_col(alpha = 0.6) +\n  scale_fill_manual(values = plot_cols, guide = \"none\") +\n  scale_colour_manual(values = plot_cols, guide = \"none\") +\n  geom_text(aes(label = percent(proportion_plays)), hjust= 1, size =5, colour = plot_cols[8]) +\n  scale_y_continuous(labels = comma, name = \"% Plays\") +\n  ggtitle(\"INDOOR OPEN STADIUMS ON SYNTHETIC ARE BAD NEWS\", subtitle = \"Injuries are far more likely here, with 7% injury rate\") +\n  coord_flip() +\n  theme_jason() +\n  theme(axis.title.y = element_blank(), axis.text.x = element_blank()) + \n  facet_wrap(~ FieldType)","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"R","language":"R","name":"ir"},"language_info":{"mimetype":"text/x-r-source","name":"R","pygments_lexer":"r","version":"3.4.2","file_extension":".r","codemirror_mode":"r"}},"nbformat":4,"nbformat_minor":1}