---
title: "Untitled"
author: "RN7"
date: "8/4/2019"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, fig.height=6, fig.width=8)
```

# Packages

```{r, message=FALSE, warning=FALSE}
pacman::p_load(dplyr, stringr, tidyr, purrr, forcats, ggplot2,
               StatsBombR, soccermatics, SBpitch, ggsoccer,
               rlang, extrafont, ggupset)
loadfonts()
```



```{r}
comps <- FreeCompetitions()

glimpse(comps)
```


# Raw data

```{r}
messi_matches_raw <- comps %>% 
  filter(competition_id ==11) %>% 
  FreeMatches()


messi_data_raw <- StatsBombFreeEvents(MatchesDF = messi_matches_raw)

glimpse(messi_data_raw)
```

# Save raw

```{r}
saveRDS(messi_data_raw, file = here::here("data/messi_data_raw.RDS"))
messi_data_raw <- readRDS(file = here::here("data/messi_data_raw.RDS"))
```


# Clean all + add season labels

```{r}
messi_data_clean <- messi_data_raw %>% 
  allclean() %>%  ## cleanlocations, goalkeeper, shot, freezeframe, defensive
  left_join(comps %>% select(season_id, season_name), by = "season_id")
```



```{r}
messi_data_clean <- messi_data_clean %>% 
  ## player name
  mutate(player.name = case_when(
    player.name == "Oleguer Presas Renom" ~ "Oleguer",
    player.name == "Xavier Hernández Creus" ~ "Xavi",
    player.name == "Carles Puyol i Saforcada" ~ "Carles Puyol",
    player.name == "Anderson Luís de Souza" ~ "Deco",
    player.name == "Rafael Márquez Álvarez" ~ "Rafa Márquez",
    player.name == "Giovanni van Bronckhorst" ~ "Gio v.Bronckhorst",
    player.name == "Samuel Eto'o Fils" ~ "Samuel Eto'o",
    player.name == "Víctor Valdés Arribas" ~ "Víctor Valdés",
    player.name == "Juliano Haus Belletti" ~ "Juliano Belletti",
    player.name == "Ludovic Giuly" ~ "Ludovic Giuly",
    player.name == "Andrés Iniesta Luján" ~ "Andrés Iniesta",
    player.name == "Ronaldo de Assis Moreira" ~ "Ronaldinho",
    player.name == "Lionel Andrés Messi Cuccittini" ~ "Lionel Messi",
    player.name == "Fernando Navarro i Corbacho" ~ "Fernando Navarro",
    player.name == "Sylvio Mendes Campos Junior" ~ "Sylvinho",
    player.name == "Damià Abella Pérez" ~ "Damià",
    player.name == "Rubén Iván Martínez Andrade" ~ "Ronaldinho",
    player.name == "Ronaldo de Assis Moreira" ~ "Rubén",
    player.name == "Thiago Motta" ~ "Thiago Motta",
    player.name == "Mark van Bommel" ~ "Mark van Bommel",
    player.name == "Henrik Larsson" ~ "Henrik Larsson",
    player.name == "José Edmílson Gomes de Moraes" ~ "Edmílson",
    player.name == "Gabriel Francisco García de la Torre" ~ "Gabri",
    player.name == "Santiago Ezquerro Marín" ~ "Santi Ezquerro",
    player.name == "Maximiliano Gastón López" ~ "Maxi López",
    player.name == "Gianluca Zambrotta" ~ "Gianluca Zambrotta",
    player.name == "Eiður Smári Guðjohnsen" ~ "Eiður Guðjohnsen",
    player.name == "Lilian Thuram" ~ "Lilian Thuram",
    player.name == "Javier Pedro Saviola Fernández" ~ "Javier Saviola",
    player.name == "Gnégnéri Yaya Touré" ~ "Yaya Touré",
    player.name == "Bojan Krkíc Pérez" ~ "Bojan",
    player.name == "Eric-Sylvain Bilal Abidal" ~ "Eric Abidal",
    player.name == "Gabriel Alejandro Milito" ~ "Gabriel Milito",
    player.name == "Giovani dos Santos Ramírez" ~ "Giovani dos Santos",
    player.name == "Víctor Vázquez Solsona" ~ "Víctor Vázquez",
    player.name == "Thierry Henry" ~ "Thierry Henry",
    player.name == "José Manuel Pinto Colorado" ~ "José Manuel Pinto",
    player.name == "Daniel Alves da Silva" ~ "Dani Alves",
    player.name == "Sergio Busquets i Burgos" ~ "Sergio Busquets",
    player.name == "Seydou Kéita" ~ "Seydou Kéita",
    player.name == "José Martín Cáceres Silva" ~ "Martín Cáceres",
    player.name == "Gerard Piqué Bernabéu" ~ "Gerard Piqué",
    player.name == "Aliaksandr Hleb" ~ "Aliaksandr Hleb",
    player.name == "Pedro Eliezer Rodríguez Ledesma" ~ "Pedro",
    player.name == "Sergio Rodríguez García" ~ "Rodri",
    player.name == "Rafael Romero Serrano" ~ "Fali",
    player.name == "José Manuel Rueda Sampedro" ~ "José Manuel Rueda",
    player.name == "Zlatan Ibrahimovic" ~ "Zlatan Ibrahimovic",
    player.name == "Dmytro Chygrynskiy" ~ "Dmytro Chygrynskiy",
    player.name == "Maxwell Scherrer Cabelino Andrade" ~ "Maxwell",
    player.name == "Jeffren Isaac Suárez Bermúdez" ~ "Jeffren",
    player.name == "Víctor Sánchez Mata" ~ "Víctor Sánchez",
    player.name == "Thiago Alcântara do Nascimento" ~ "Thiago Alcântara",
    player.name == "David Villa Sánchez" ~ "David Villa",
    player.name == "Javier Alejandro Mascherano" ~ "Javier Mascherano",
    player.name == "Andreu Fontàs Prat" ~ "Andreu Fontàs",
    player.name == "Ibrahim Afellay" ~ "Ibrahim Afellay",
    player.name == "Manuel Agudo Durán" ~ "Nolito",
    player.name == "Marc Bartra Aregall" ~ "Marc Bartra",
    player.name == "Adriano Correia Claro" ~ "Adriano",
    player.name == "Martín Montoya Torralbo" ~ "Martín Montoya",
    player.name == "Jonathan dos Santos Ramírez" ~ "Jonathan dos Santos",
    player.name == "Francesc Fàbregas i Soler" ~ "Cesc Fàbregas",
    player.name == "Alexis Alejandro Sánchez Sánchez" ~ "Alexis Sánchez",
    player.name == "Juan Isaac Cuenca López" ~ "Isaac Cuenca",
    player.name == "Gerard Deulofeu Lázaro" ~ "Gerard Deulofeu",
    player.name == "Cristian Tello" ~ "Cristian Tello",
    player.name == "Sergi Roberto Carnicer" ~ "Sergi Roberto",
    player.name == "Marc Muniesa Martínez" ~ "Marc Muniesa",
    TRUE ~ player.name
  )) %>% 
  ## pass.recipient.name
  mutate(pass.recipient.name = case_when(
    pass.recipient.name == "Oleguer Presas Renom" ~ "Oleguer",
    pass.recipient.name == "Xavier Hernández Creus" ~ "Xavi",
    pass.recipient.name == "Carles Puyol i Saforcada" ~ "Carles Puyol",
    pass.recipient.name == "Anderson Luís de Souza" ~ "Deco",
    pass.recipient.name == "Rafael Márquez Álvarez" ~ "Rafa Márquez",
    pass.recipient.name == "Giovanni van Bronckhorst" ~ "Gio v.Bronckhorst",
    pass.recipient.name == "Samuel Eto'o Fils" ~ "Samuel Eto'o",
    pass.recipient.name == "Víctor Valdés Arribas" ~ "Víctor Valdés",
    pass.recipient.name == "Juliano Haus Belletti" ~ "Juliano Belletti",
    pass.recipient.name == "Ludovic Giuly" ~ "Ludovic Giuly",
    pass.recipient.name == "Andrés Iniesta Luján" ~ "Andrés Iniesta",
    pass.recipient.name == "Ronaldo de Assis Moreira" ~ "Ronaldinho",
    pass.recipient.name == "Lionel Andrés Messi Cuccittini" ~ "Lionel Messi",
    pass.recipient.name == "Fernando Navarro i Corbacho" ~ "Fernando Navarro",
    pass.recipient.name == "Sylvio Mendes Campos Junior" ~ "Sylvinho",
    pass.recipient.name == "Damià Abella Pérez" ~ "Damià",
    pass.recipient.name == "Rubén Iván Martínez Andrade" ~ "Ronaldinho",
    pass.recipient.name == "Ronaldo de Assis Moreira" ~ "Rubén",
    pass.recipient.name == "Thiago Motta" ~ "Thiago Motta",
    pass.recipient.name == "Mark van Bommel" ~ "Mark van Bommel",
    pass.recipient.name == "Henrik Larsson" ~ "Henrik Larsson",
    pass.recipient.name == "José Edmílson Gomes de Moraes" ~ "Edmílson",
    pass.recipient.name == "Gabriel Francisco García de la Torre" ~ "Gabri",
    pass.recipient.name == "Santiago Ezquerro Marín" ~ "Santi Ezquerro",
    pass.recipient.name == "Maximiliano Gastón López" ~ "Maxi López",
    pass.recipient.name == "Gianluca Zambrotta" ~ "Gianluca Zambrotta",
    pass.recipient.name == "Eiður Smári Guðjohnsen" ~ "Eiður Guðjohnsen",
    pass.recipient.name == "Lilian Thuram" ~ "Lilian Thuram",
    pass.recipient.name == "Javier Pedro Saviola Fernández" ~ "Javier Saviola",
    pass.recipient.name == "Gnégnéri Yaya Touré" ~ "Yaya Touré",
    pass.recipient.name == "Bojan Krkíc Pérez" ~ "Bojan",
    pass.recipient.name == "Eric-Sylvain Bilal Abidal" ~ "Eric Abidal",
    pass.recipient.name == "Gabriel Alejandro Milito" ~ "Gabriel Milito",
    pass.recipient.name == "Giovani dos Santos Ramírez" ~ "Giovani dos Santos",
    pass.recipient.name == "Víctor Vázquez Solsona" ~ "Víctor Vázquez",
    pass.recipient.name == "Thierry Henry" ~ "Thierry Henry",
    pass.recipient.name == "José Manuel Pinto Colorado" ~ "José Manuel Pinto",
    pass.recipient.name == "Daniel Alves da Silva" ~ "Dani Alves",
    pass.recipient.name == "Sergio Busquets i Burgos" ~ "Sergio Busquets",
    pass.recipient.name == "Seydou Kéita" ~ "Seydou Kéita",
    pass.recipient.name == "José Martín Cáceres Silva" ~ "Martín Cáceres",
    pass.recipient.name == "Gerard Piqué Bernabéu" ~ "Gerard Piqué",
    pass.recipient.name == "Aliaksandr Hleb" ~ "Aliaksandr Hleb",
    pass.recipient.name == "Pedro Eliezer Rodríguez Ledesma" ~ "Pedro",
    pass.recipient.name == "Sergio Rodríguez García" ~ "Rodri",
    pass.recipient.name == "Rafael Romero Serrano" ~ "Fali",
    pass.recipient.name == "José Manuel Rueda Sampedro" ~ "José Manuel Rueda",
    pass.recipient.name == "Zlatan Ibrahimovic" ~ "Zlatan Ibrahimovic",
    pass.recipient.name == "Dmytro Chygrynskiy" ~ "Dmytro Chygrynskiy",
    pass.recipient.name == "Maxwell Scherrer Cabelino Andrade" ~ "Maxwell",
    pass.recipient.name == "Jeffren Isaac Suárez Bermúdez" ~ "Jeffren",
    pass.recipient.name == "Víctor Sánchez Mata" ~ "Víctor Sánchez",
    pass.recipient.name == "Thiago Alcântara do Nascimento" ~ "Thiago Alcântara",
    pass.recipient.name == "David Villa Sánchez" ~ "David Villa",
    pass.recipient.name == "Javier Alejandro Mascherano" ~ "Javier Mascherano",
    pass.recipient.name == "Andreu Fontàs Prat" ~ "Andreu Fontàs",
    pass.recipient.name == "Ibrahim Afellay" ~ "Ibrahim Afellay",
    pass.recipient.name == "Manuel Agudo Durán" ~ "Nolito",
    pass.recipient.name == "Marc Bartra Aregall" ~ "Marc Bartra",
    pass.recipient.name == "Adriano Correia Claro" ~ "Adriano",
    pass.recipient.name == "Martín Montoya Torralbo" ~ "Martín Montoya",
    pass.recipient.name == "Jonathan dos Santos Ramírez" ~ "Jonathan dos Santos",
    pass.recipient.name == "Francesc Fàbregas i Soler" ~ "Cesc Fàbregas",
    pass.recipient.name == "Alexis Alejandro Sánchez Sánchez" ~ "Alexis Sánchez",
    pass.recipient.name == "Juan Isaac Cuenca López" ~ "Isaac Cuenca",
    pass.recipient.name == "Gerard Deulofeu Lázaro" ~ "Gerard Deulofeu",
    pass.recipient.name == "Cristian Tello" ~ "Cristian Tello",
    pass.recipient.name == "Sergi Roberto Carnicer" ~ "Sergi Roberto",
    pass.recipient.name == "Marc Muniesa Martínez" ~ "Marc Muniesa",
    TRUE ~ pass.recipient.name
  ))
```



# Save clean

```{r}
saveRDS(messi_data_clean, file = here::here("data/messi_data_clean.RDS"))
messi_data_clean <- readRDS(file = here::here("data/messi_data_clean.RDS"))
```

## box - Messi

```{r}
messi_pass_received_box <- messi_data_clean %>% 
  mutate(pass.outcome.name = fct_explicit_na(pass.outcome.name, "Complete")) %>%
  filter(type.name == "Pass",
         pass.outcome.name == "Complete",
         pass.recipient.id == 5503,
         !play_pattern.name %in% c("From Corner", "From Free Kick",
                                   "From Throw In"),
         pass.end_location.x >= 102 & pass.end_location.y <= 62 &
           pass.end_location.y >= 18) %>% 
  select(player.name, pass.recipient.name, 
         season_id, season_name,
         position.name, position.id,
         location.x, location.y,
         pass.end_location.x, pass.end_location.y,
         contains("pass")) %>% 
  group_by(season_name) %>% 
  add_count(player.name, pass.recipient.name, name = "pass_num") %>% 
  ungroup() %>% 
  mutate(player.name = case_when(
    player.name != "Lionel Messi" ~ 
      glue::glue("{player.name}: {pass_num}")),
    pass.recipient.name = "Lionel Messi") %>% 
  mutate(pass_duo = map2(player.name, pass.recipient.name, ~c(.x, .y)))
```

# passmaps

```{r}
messi_alves_1112 <- messi_pass_received_box %>% 
  filter(season_name == "2011/2012") %>% 
  mutate(player.name = player.name %>% str_replace_all(., "\\: [0-9]*", "")) %>% 
  filter(player.name == "Dani Alves") %>% 
  select(player.name, pass.recipient.name, 
         location.x, location.y, 
         pass.end_location.x, pass.end_location.y,
         pass.length, pass.angle,
         pass.switch, pass.cross, pass.cut_back, 
         pass.through_ball, pass.shot_assist, pass.goal_assist) %>% 
  pivot_longer(-c(player.name, pass.recipient.name,
                  location.x, location.y, 
                  pass.end_location.x, pass.end_location.y,
                  pass.length, pass.angle),
               names_to = "pass_type", values_to = "blah") %>% 
  ## filter out pass.shot_assist and pass.goal_assist as double up
  filter(pass_type %in% c("pass.shot_assist", "pass.goal_assist"),
         blah == TRUE)
```


```{r}
messi_alves_1112 %>% 
    select(player.name, pass.recipient.name, 
           location.x, location.y, 
           pass.end_location.x, pass.end_location.y,
           pass.length, pass.angle,
           pass.cross, pass.cut_back, 
           pass.through_ball, pass.shot_assist, pass.goal_assist) %>% 
    distinct(player.name, location.x, pass.angle, .keep_all = TRUE)
```


- some passes have NO labels so get filtered out... 

### ggsoccer

```{r}
messi_alves_1112 %>% 
  ggplot() +
  annotate_pitch(dimensions = pitch_statsbomb) +
  geom_segment(aes(x = location.x, y = location.y, 
                   xend = pass.end_location.x, yend = pass.end_location.y,
                   color = pass_type),      
               lineend = "round", size = 0.6,
               arrow = arrow(length = unit(0.08, "inches"))) + 
  geom_point(x = 80, y = 60) +
  geom_point(x = 0, y = 80, color = "blue", size = 5) +
  geom_text(x = 0, y = 80, hjust = 0,
            label = "x = 0, y = 80", size = 5) +
  geom_point(x = 0, y = 0, color = "green", size = 5) +
  geom_text(x = 0, y = 0, hjust = 0,
            label = "x = 0, y = 0", size = 5) +
  geom_point(x = 80, y = 0, color = "red", size = 5) +
  geom_text(x = 80, y = 0, hjust = 0,
            label = "x = 80, y = 0", size = 5) +
  theme_pitch() +
  direction_label(x_label = 60) +
  labs(title = "Completed Box Passes to Messi Leading to Shots (2011/2012)",
       subtitle = "Dani Alves") +  
  theme(text = element_text(family = "Roboto Condensed"))
```


* Fixed coords

```{r}
messi_alves_1112 %>% 
  ## swap the y coords
  mutate(rlocation.y = (location.y - 80) * -1,
         rpass.end_location.y = (pass.end_location.y - 80) * -1) %>% 
  ggplot() +
  annotate_pitch(dimensions = pitch_statsbomb) +
  geom_segment(aes(x = location.x, y = rlocation.y, 
                   xend = pass.end_location.x, yend = rpass.end_location.y,
                   color = pass_type),      
               lineend = "round", size = 0.6,
               arrow = arrow(length = unit(0.08, "inches"))) + 
  geom_point(x = 80, y = 60) +
  geom_point(x = 0, y = 80, color = "blue", size = 5) +
  geom_text(x = 0, y = 80, hjust = 0,
            label = "x = 0, y = 80", size = 5) +
  geom_point(x = 0, y = 0, color = "green", size = 5) +
  geom_text(x = 0, y = 0, hjust = 0,
            label = "x = 0, y = 0", size = 5) +
  geom_point(x = 80, y = 0, color = "red", size = 5) +
  geom_text(x = 80, y = 0, hjust = 0,
            label = "x = 80, y = 0", size = 5) +
  theme_pitch() +
  direction_label(x_label = 60) +
  labs(title = "Completed Box Passes to Messi Leading to Shots (REVERSED Y COORD)",
       subtitle = "Dani Alves (2011/2012)") +  
  theme(text = element_text(family = "Roboto Condensed"))
```

### SB pitch

```{r}
create_Pitch() +
  geom_segment(data = messi_alves_1112,
               aes(x = location.x, y = location.y,   
                   xend = pass.end_location.x, yend = pass.end_location.y,
                   color = pass.length),      
               lineend = "round", size = 0.6,
               arrow = arrow(length = unit(0.08, "inches"))) + 
  labs(title = "Completed Box Passes to Messi (2011/2012)", 
       subtitle = glue::glue("Daniel Alves: {messi_alves_1112$pass_num}")) +  
  coord_fixed(ratio = 105/100) +
  theme(text = element_text(family = "Roboto Condensed"))
```

* Fixed coords

```{r}
create_Pitch() +
  geom_segment(data = messi_alves_1112 %>% 
                 mutate(rlocation.y = (location.y - 80) * -1,
                        rpass.end_location.y = (pass.end_location.y - 80) * -1),
               aes(x = location.x, y = rlocation.y,   
                   xend = pass.end_location.x, yend = rpass.end_location.y,
                   color = pass.length),      
               lineend = "round", size = 0.6,
               arrow = arrow(length = unit(0.08, "inches"))) + 
  labs(title = "Completed Box Passes to Messi (2011/2012)", 
       subtitle = glue::glue("Daniel Alves: {messi_alves_1112$pass_num}")) +  
  coord_fixed(ratio = 105/100) +
  theme(text = element_text(family = "Roboto Condensed"))
```

### soccermatics

```{r fig.height=6, fig.width=8}
soccerPitch(arrow = "r",
            lengthPitch = 120, widthPitch = 80,
            title = "Dani Alves to Messi") +
  geom_segment(data = messi_alves_1112,
               aes(x = location.x, y = location.y,
                   xend = pass.end_location.x, yend = pass.end_location.y),
               lineend = "round", size = 0.6,
               arrow = arrow(length = unit(0.08, "inches"))) +
  geom_point(data = messi_alves_1112,
               aes(x = location.x, y = location.y)) +
  geom_point(x = 0, y = 80, color = "blue", size = 5) +
  geom_text(x = 0, y = 80, hjust = 0,
            label = "x = 0, y = 80", size = 5) +
  geom_point(x = 0, y = 0, color = "green", size = 5) +
  geom_text(x = 0, y = 0, hjust = 0,
            label = "x = 0, y = 0", size = 5) +
  geom_point(x = 80, y = 0, color = "red", size = 5) +
  geom_text(x = 80, y = 0, hjust = 0,
            label = "x = 80, y = 0", size = 5)
```

```{r}
ggsave(filename = "dalvesmessi1112.png", height = 6, width = 8)
```


* fixed coords

```{r fig.height=6, fig.width=8}
soccerPitch(arrow = "r",
            lengthPitch = 120, widthPitch = 80,
            title = "Dani Alves to Messi") +
  geom_segment(data = messi_alves_1112 %>% 
                 mutate(rlocation.y = (location.y - 80) * -1,
                        rpass.end_location.y = (pass.end_location.y - 80) * -1),
               aes(x = location.x, y = rlocation.y,   
                   xend = pass.end_location.x, yend = rpass.end_location.y),      
               lineend = "round", size = 0.6,
               arrow = arrow(length = unit(0.08, "inches"))) +
  geom_point(data = messi_alves_1112 %>% 
               mutate(rlocation.y = (location.y - 80) * -1,
                        rpass.end_location.y = (pass.end_location.y - 80) * -1),
               aes(x = location.x, y = rlocation.y)) +
  geom_point(x = 0, y = 80, color = "blue", size = 5) +
  geom_text(x = 0, y = 80, hjust = 0,
            label = "x = 0, y = 80", size = 5) +
  geom_point(x = 0, y = 0, color = "green", size = 5) +
  geom_text(x = 0, y = 0, hjust = 0,
            label = "x = 0, y = 0", size = 5) +
  geom_point(x = 80, y = 0, color = "red", size = 5) +
  geom_text(x = 80, y = 0, hjust = 0,
            label = "x = 80, y = 0", size = 5)
```


```{r}
ggsave(filename = "dalvesmessi1112REVERSED.png", height = 6, width = 8)
```


### coord-flipped

```{r}
soccerPitch(arrow = "r",
            lengthPitch = 120, widthPitch = 80,
            title = "Dani Alves to Messi") +
  geom_segment(data = messi_alves_1112,
               aes(x = location.x, y = location.y,
                   xend = pass.end_location.x, yend = pass.end_location.y),
               lineend = "round", size = 0.6,
               arrow = arrow(length = unit(0.08, "inches"))) +
  geom_point(data = messi_alves_1112,
               aes(x = location.x, y = location.y)) +
  geom_point(x = 0, y = 80, color = "blue", size = 5) +
  geom_text(x = 0, y = 80, hjust = 0,
            label = "x = 0, y = 80", size = 5) +
  geom_point(x = 0, y = 0, color = "green", size = 5) +
  geom_text(x = 0, y = 0, hjust = 0,
            label = "x = 0, y = 0", size = 5) +
  geom_point(x = 80, y = 0, color = "red", size = 5) +
  geom_text(x = 80, y = 0, hjust = 0,
            label = "x = 80, y = 0", size = 5) +
  coord_flip(xlim = c(49, 132),
             ylim = c(-5, 105))
```


```{r}
ggsave(filename = "dalvesmessi1112VERTICAL.png", height = 6, width = 8)
```

