Fit and plot trajectories

  • Note that the fitting is done by ggplot2
plot_trajectories <- function(player, n_similar = 5, ncol) { 
  flnames <- unlist(str_split(player, " "))
  
  player <- People |> 
    filter(nameFirst == flnames[1], nameLast == flnames[2]) |>
    select(playerID)

  player_list <- player |>
    pull(playerID) |>
    similar(n_similar) |>
    pull(playerID)
  
  Batting_new <- batting_2000 |> 
    filter(playerID %in% player_list) |>
    mutate(Name = paste(nameFirst, nameLast))
  
    ggplot(Batting_new, aes(Age, OPS)) + 
      geom_smooth(
        method = "lm",
        formula = y ~ x + I(x^2),
        linewidth = 1.5
      ) +
      facet_wrap(vars(Name), ncol = ncol) + 
      theme_bw()
}