TimStats commited on
Commit
458ec6e
·
verified ·
1 Parent(s): e637d81

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +549 -47
app.R CHANGED
@@ -1,58 +1,560 @@
 
1
  library(shiny)
2
- library(bslib)
3
- library(dplyr)
4
  library(ggplot2)
 
 
 
 
 
 
 
5
 
6
- df <- readr::read_csv("penguins.csv")
7
- # Find subset of columns that are suitable for scatter plot
8
- df_num <- df |> select(where(is.numeric), -Year)
9
-
10
- ui <- page_sidebar(
11
- theme = bs_theme(bootswatch = "minty"),
12
- title = "Penguins explorer",
13
- sidebar = sidebar(
14
- varSelectInput("xvar", "X variable", df_num, selected = "Bill Length (mm)"),
15
- varSelectInput("yvar", "Y variable", df_num, selected = "Bill Depth (mm)"),
16
- checkboxGroupInput("species", "Filter by species",
17
- choices = unique(df$Species), selected = unique(df$Species)
18
- ),
19
- hr(), # Add a horizontal rule
20
- checkboxInput("by_species", "Show species", TRUE),
21
- checkboxInput("show_margins", "Show marginal plots", TRUE),
22
- checkboxInput("smooth", "Add smoother"),
23
- ),
24
- plotOutput("scatter")
25
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
- server <- function(input, output, session) {
28
- subsetted <- reactive({
29
- req(input$species)
30
- df |> filter(Species %in% input$species)
31
- })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
- output$scatter <- renderPlot(
34
- {
35
- p <- ggplot(subsetted(), aes(!!input$xvar, !!input$yvar)) +
36
- theme_light() +
37
- list(
38
- theme(legend.position = "bottom"),
39
- if (input$by_species) aes(color = Species),
40
- geom_point(),
41
- if (input$smooth) geom_smooth()
42
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
- if (input$show_margins) {
45
- margin_type <- if (input$by_species) "density" else "histogram"
46
- p <- p |> ggExtra::ggMarginal(
47
- type = margin_type, margins = "both",
48
- size = 8, groupColour = input$by_species, groupFill = input$by_species
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
- p
53
- },
54
- res = 100
55
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  }
57
 
58
- shinyApp(ui, server)
 
 
1
+ # app.R
2
  library(shiny)
3
+ library(tidyverse)
 
4
  library(ggplot2)
5
+ library(dplyr)
6
+ library(patchwork)
7
+ library(showtext)
8
+ library(magick)
9
+ library(grid)
10
+ library(gridExtra)
11
+ library(gtable)
12
 
13
+ is_barrel <- function(df) {
14
+ df$hit_speedr <- round(df$hit_speed)
15
+ df <- df |>
16
+ mutate(barrel = ifelse((hit_speedr >= 124) &
17
+ (hit_angle >= 0 & hit_angle <= 50),1,0)) |>
18
+ mutate(barrel = ifelse((hit_speedr == 123) &
19
+ (hit_angle >= 1 & hit_angle <= 50),1,barrel)) |>
20
+ mutate(barrel = ifelse((hit_speedr == 122) &
21
+ (hit_angle >= 2 & hit_angle <= 50),1,barrel)) |>
22
+ mutate(barrel = ifelse((hit_speedr == 121) &
23
+ (hit_angle >= 3 & hit_angle <= 50),1,barrel)) |>
24
+ mutate(barrel = ifelse((hit_speedr == 120) &
25
+ (hit_angle >= 4 & hit_angle <= 50),1,barrel)) |>
26
+ mutate(barrel = ifelse((hit_speedr == 119) &
27
+ (hit_angle >= 5 & hit_angle <= 50),1,barrel)) |>
28
+ mutate(barrel = ifelse((hit_speedr == 118) &
29
+ (hit_angle >= 6 & hit_angle <= 50),1,barrel)) |>
30
+ mutate(barrel = ifelse((hit_speedr == 117) &
31
+ (hit_angle >= 7 & hit_angle <= 50),1,barrel)) |>
32
+ mutate(barrel = ifelse((hit_speedr == 116) &
33
+ (hit_angle >= 8 & hit_angle <= 50),1,barrel)) |>
34
+ mutate(barrel = ifelse((hit_speedr == 115) &
35
+ (hit_angle >= 9 & hit_angle <= 50),1,barrel)) |>
36
+ mutate(barrel = ifelse((hit_speedr == 114) &
37
+ (hit_angle >= 10 & hit_angle <= 50),1,barrel)) |>
38
+ mutate(barrel = ifelse((hit_speedr == 113) &
39
+ (hit_angle >= 11 & hit_angle <= 50),1,barrel)) |>
40
+ mutate(barrel = ifelse((hit_speedr == 112) &
41
+ (hit_angle >= 12 & hit_angle <= 50),1,barrel)) |>
42
+ mutate(barrel = ifelse((hit_speedr == 111) &
43
+ (hit_angle >= 13 & hit_angle <= 50),1,barrel)) |>
44
+ mutate(barrel = ifelse((hit_speedr == 110) &
45
+ (hit_angle >= 14 & hit_angle <= 48),1,barrel)) |>
46
+ mutate(barrel = ifelse((hit_speedr == 109) &
47
+ (hit_angle >= 15 & hit_angle <= 46),1,barrel)) |>
48
+ mutate(barrel = ifelse((hit_speedr == 108) &
49
+ (hit_angle >= 16 & hit_angle <= 45),1,barrel)) |>
50
+ mutate(barrel = ifelse((hit_speedr == 107) &
51
+ (hit_angle >= 17 & hit_angle <= 43),1,barrel)) |>
52
+ mutate(barrel = ifelse((hit_speedr == 106) &
53
+ (hit_angle >= 18 & hit_angle <= 42),1,barrel)) |>
54
+ mutate(barrel = ifelse((hit_speedr == 105) &
55
+ (hit_angle >= 19 & hit_angle <= 40),1,barrel)) |>
56
+ mutate(barrel = ifelse((hit_speedr == 104) &
57
+ (hit_angle >= 20 & hit_angle <= 39),1,barrel)) |>
58
+ mutate(barrel = ifelse((hit_speedr == 103) &
59
+ (hit_angle >= 21 & hit_angle <= 37),1,barrel)) |>
60
+ mutate(barrel = ifelse((hit_speedr == 102) &
61
+ (hit_angle >= 22 & hit_angle <= 36),1,barrel)) |>
62
+ mutate(barrel = ifelse((hit_speedr == 101) &
63
+ (hit_angle >= 23 & hit_angle <= 34),1,barrel)) |>
64
+ mutate(barrel = ifelse((hit_speedr == 100) &
65
+ (hit_angle >= 24 & hit_angle <= 33),1,barrel)) |>
66
+ mutate(barrel = ifelse((hit_speedr == 99) &
67
+ (hit_angle >= 25 & hit_angle <= 31),1,barrel)) |>
68
+ mutate(barrel = ifelse((hit_speedr == 98) &
69
+ (hit_angle >= 26 & hit_angle <= 30),1,barrel)) |>
70
+ select(-hit_speedr)
71
+ return(df)
72
+ }
73
 
74
+ apply_percentile_calcs <- function(data) {
75
+ # List of columns to apply percent_rank
76
+ percent_rank_cols <- c("Z-Con%", "Z-Swing%", "O-Con%", "Avg EV", "Max EV", "EV90", "Barrel%", "Swing%", "wOBA",
77
+ "wOBACON","xwOBA","xwOBACON")
78
+
79
+ # List of columns to apply inverse percent_rank
80
+ inverse_percent_rank_cols <- c("Chase%", "Whiff%", "stdev(LA)", "SwStr%")
81
+
82
+ # Create an empty list to store results
83
+ percentile_list <- list()
84
+
85
+ # Calculate regular percentiles
86
+ for(col in percent_rank_cols) {
87
+ percentile_list[[col]] <- data.frame(
88
+ `Batter Name` = data[["Batter Name"]], # Using [[ ]] to preserve exact column name
89
+ `Batter ID` = data[["Batter ID"]], # Using [[ ]] to preserve exact column name
90
+ metric = col,
91
+ percentile = round(percent_rank(data[[col]]) * 100),
92
+ value = data[[col]],
93
+ stringsAsFactors = FALSE
94
+ )
95
+ }
96
+
97
+ # Calculate inverse percentiles
98
+ for(col in inverse_percent_rank_cols) {
99
+ percentile_list[[col]] <- data.frame(
100
+ `Batter Name` = data[["Batter Name"]], # Using [[ ]] to preserve exact column name
101
+ `Batter ID` = data[["Batter ID"]], # Using [[ ]] to preserve exact column name
102
+ metric = col,
103
+ percentile = round((1 - percent_rank(data[[col]])) * 100),
104
+ value = data[[col]],
105
+ stringsAsFactors = FALSE
106
+ )
107
+ }
108
+
109
+ # Combine all results into one data frame
110
+ result <- do.call(rbind, percentile_list)
111
+
112
+ # Reset row names
113
+ rownames(result) <- NULL
114
+
115
+ return(result)
116
+ }
117
 
118
+ get_player_image <- function(player_id) {
119
+ # Try MLB silo image first
120
+ silo_url <- sprintf("https://img.mlbstatic.com/mlb-photos/image/upload/w_200,q_auto:best/v1/people/%s/headshot/silo/current", player_id)
121
+
122
+ # Check if silo works
123
+ silo_result <- tryCatch({
124
+ response <- httr::HEAD(silo_url)
125
+ httr::status_code(response) == 200
126
+ }, error = function(e) FALSE)
127
+
128
+ # If silo fails, use MiLB with correct formatting
129
+ if (!silo_result) {
130
+ return(sprintf("https://img.mlbstatic.com/mlb-photos/image/upload/c_fill,g_auto,b_white,ar_1:1/w_180/v1/people/%s/headshot/milb/current", player_id))
131
+ }
132
+
133
+ # Return silo if it worked
134
+ return(silo_url)
135
+ }
136
+
137
+ get_player_info <- function(player_id, season, level = "MLB") {
138
+ # Initialize return values
139
+ team <- "MLB"
140
+ position <- NA
141
+
142
+ # If MLB level, use original endpoint
143
+ if(level == "MLB") {
144
+ url <- paste0("https://statsapi.mlb.com/api/v1/people/", player_id,
145
+ "/stats?stats=season&season=", season, "&group=hitting")
146
+
147
+ response <- httr::GET(url)
148
+ data <- httr::content(response, "parsed")
149
+
150
+ if(length(data$stats) > 0 && length(data$stats[[1]]$splits) > 0) {
151
+ team <- data$stats[[1]]$splits[[length(data$stats[[1]]$splits)]]$team$name
152
+ }
153
+ } else {
154
+ # For minor leagues, get player info from sports endpoint
155
+ sport_code <- if(level == "AAA") "11" else "14" # 11 for AAA, 14 for FSL
156
+ url <- paste0("https://statsapi.mlb.com/api/v1/sports/", sport_code, "/players?season=", season)
157
+
158
+ response <- httr::GET(url)
159
+ # Convert response to data frame
160
+ players_df <- jsonlite::fromJSON(rawToChar(response$content), flatten = TRUE)$people
161
+
162
+ # Find player directly
163
+ found_player <- players_df[players_df$id == player_id, ]
164
+
165
+ if(nrow(found_player) > 0) {
166
+ team_id <- found_player$currentTeam.id
167
+
168
+ # Get parent org using team id
169
+ team_url <- paste0("https://statsapi.mlb.com/api/v1/teams/", team_id, "?season=", season)
170
+ team_response <- httr::GET(team_url)
171
+ team_data <- jsonlite::fromJSON(rawToChar(team_response$content))
172
+
173
+ team <- team_data$teams$parentOrgName
174
+ }
175
+ }
176
+
177
+ # Get position info (same for all levels)
178
+ url2 <- paste0("https://statsapi.mlb.com/api/v1/people/", player_id)
179
+ response2 <- httr::GET(url2)
180
+ data2 <- httr::content(response2, "parsed")
181
+
182
+ if(length(data2$people) > 0) {
183
+ full_position <- data2$people[[1]]$primaryPosition$name
184
+ position <- case_when(
185
+ full_position == "First Base" ~ "1B",
186
+ full_position == "Second Base" ~ "2B",
187
+ full_position == "Third Base" ~ "3B",
188
+ full_position == "Shortstop" ~ "SS",
189
+ full_position == "Catcher" ~ "C",
190
+ full_position == "Left Field" ~ "LF",
191
+ full_position == "Center Field" ~ "CF",
192
+ full_position == "Right Field" ~ "RF",
193
+ full_position == "Designated Hitter" ~ "DH",
194
+ full_position == "Pitcher" ~ "P",
195
+ full_position == "Two-Way Player" ~ "TWP",
196
+ TRUE ~ as.character(full_position)
197
+ )
198
+ }
199
+
200
+ return(list(
201
+ team = team,
202
+ position = position
203
+ ))
204
+ }
205
+ download_private_csv <- function(repo_id, filename) {
206
+ url <- paste0("https://huggingface.co/datasets/", repo_id, "/resolve/main/", filename)
207
+ response <- GET(url, add_headers(Authorization = paste("Bearer", Sys.getenv("GETCSV"))))
208
+
209
+ if (status_code(response) == 200) {
210
+ content <- content(response, "text")
211
+ con <- textConnection(content)
212
+
213
+ # Try different read options
214
+ data <- read.csv(con,
215
+ header = TRUE,
216
+ check.names = FALSE, # This prevents R from modifying column names
217
+ fileEncoding = "UTF-8",
218
+ stringsAsFactors = FALSE)
219
+ close(con)
220
+ return(data)
221
+ } else {
222
+ stop("Failed to download dataset")
223
+ }
224
+ }
225
+ MLB <- download_private_csv("TimStats/StatcastDataAll", "MLB.csv")
226
+ AAA <- download_private_csv("TimStats/StatcastDataAll", "AAA.csv")
227
+ FSLAll <- download_private_csv("TimStats/StatcastDataAll", "FSL.csv")
228
+
229
+ temp_players <- MLB %>% filter(season == 2024)
230
+ MLBC <- rbind(MLB,AAA,FSLAll)
231
+ data <- is_barrel(MLBC) %>%
232
+ mutate(
233
+ BBE = case_when(description %in% c('In play, run(s)','In play, out(s)','In play, no out') ~ TRUE, TRUE ~ FALSE),
234
+ Swing = case_when(description %in% c('Foul','Foul Bunt','Foul Pitchout','Foul Tip',
235
+ 'In play, run(s)','In play, out(s)','In play, no out',
236
+ 'Swinging Strike','Swinging Strike (Blocked)',
237
+ 'Missed Bunt') ~ TRUE, TRUE ~ FALSE),
238
+ Contact = case_when(description %in% c('In play, run(s)','In play, out(s)','In play, no out',
239
+ 'Foul','Foul Bunt','Foul Pitchout') ~ TRUE, TRUE ~ FALSE),
240
+ Whiff = case_when(description %in% c('Swinging Strike','Swinging Strike (Blocked)',
241
+ 'Missed Bunt','Foul Tip') ~ TRUE, TRUE ~ FALSE),
242
+ IZ = ifelse(zone <= 9, TRUE, FALSE),
243
+ Single = case_when(result == "Single" & BBE == TRUE ~ TRUE, TRUE ~ FALSE),
244
+ Double = case_when(result == "Double" & BBE == TRUE ~ TRUE, TRUE ~ FALSE),
245
+ Triple = case_when(result == "Triple" & BBE == TRUE ~ TRUE, TRUE ~ FALSE),
246
+ `Home Run` = case_when(result == "Home Run" & BBE == TRUE ~ TRUE, TRUE ~ FALSE),
247
+ Walk = case_when(balls >= 4 & result == "Walk" ~ TRUE, TRUE ~ FALSE),
248
+ HBP = case_when(description == "Hit By Pitch" & result == "Hit By Pitch" ~ TRUE, TRUE ~ FALSE),
249
+ Strikeout = case_when(strikes >= 3 & result %in% c("Strikeout",'Stikeout Double Play') ~ TRUE, TRUE ~ FALSE),
250
+ Sac = case_when(BBE == TRUE & result %in% c('Sac Fly','Sac Bunt',
251
+ 'Sac Fly Double Play','Sac Bunt Double Play') ~ TRUE, TRUE ~ FALSE),
252
+ IBB = case_when(pitchNum == 1 & result == "Intent Walk" ~ TRUE, TRUE ~ FALSE),
253
+ AB = Strikeout + BBE - Sac,
254
+ PA = AB + Walk + HBP + IBB
255
+ ) %>%
256
+ group_by(`Batter Name`,`Batter ID`,season,level) %>%
257
+ summarise(
258
+ BIP = sum(BBE,na.rm = TRUE),
259
+ wOBA = round((sum(Single,na.rm = TRUE) * .882 + sum(Double, na.rm = TRUE) * 1.254 +
260
+ sum(Triple,na.rm = TRUE) * 1.59 + sum(`Home Run`,na.rm = TRUE) * 2.05 +
261
+ sum(Walk,na.rm = TRUE) * .689 + sum(HBP,na.rm = TRUE) * .720) /
262
+ (sum(PA,na.rm = TRUE) - sum(IBB,na.rm = TRUE)), 3),
263
+ wOBACON = round((sum(Single,na.rm = TRUE) * .882 + sum(Double, na.rm = TRUE) * 1.254 +
264
+ sum(Triple,na.rm = TRUE) * 1.59 + sum(`Home Run`,na.rm = TRUE) * 2.05 )/
265
+ sum(BBE,na.rm = TRUE), 3),
266
+ xwOBA = round(mean(expected_woba,na.rm = TRUE), 3),
267
+ xwOBACON = round(mean(expected_woba[BBE == TRUE],na.rm = TRUE), 3),
268
+ `Avg EV` = round(mean(hit_speed,na.rm = TRUE), 1),
269
+ EV90 = round(quantile(hit_speed,0.9,na.rm = TRUE), 1),
270
+ `Max EV` = round(max(hit_speed,na.rm = TRUE), 1),
271
+ 'stdev(LA)' = round(sd(hit_angle,na.rm = TRUE), 1),
272
+ 'Barrel%' = round(100 * mean(barrel[Swing == TRUE],na.rm = TRUE), 1),
273
+ "Z-Con%" = round(100 * mean(Contact[IZ == TRUE & Swing == TRUE],na.rm = TRUE), 1),
274
+ "Z-Swing%" = round(100 * mean(Swing[IZ == TRUE],na.rm = TRUE), 1),
275
+ "O-Con%" = round(100 * mean(Contact[IZ == FALSE & Swing == TRUE],na.rm = TRUE), 1),
276
+ "Chase%" = round(100 * mean(Swing[IZ == FALSE],na.rm = TRUE), 1),
277
+ "Whiff%" = round(100 * mean(Whiff[Swing == TRUE],na.rm = TRUE), 1),
278
+ "Swing%" = round(100 * mean(Swing,na.rm = TRUE), 1),
279
+ "SwStr%" = round(100 * mean(Whiff,na.rm = TRUE), 1)
280
+ )
281
 
282
+ # UI definition
283
+ ui <- fluidPage(
284
+ titlePanel(NULL, windowTitle = "Baseball Stats Visualization"),
285
+
286
+ sidebarLayout(
287
+ sidebarPanel(
288
+ selectInput("szn", "Season:", c(2024, 2023, 2022, 2021, 2021)),
289
+ selectInput("level", "Level:", c("MLB", "AAA", "FSL")),
290
+ selectInput("type", "Player Type:", c("Batter", "Pitcher")),
291
+ selectInput("player", "Player:", choices = unique(temp_players$`Batter Name`)),
292
+ # Add toggle for custom team
293
+ checkboxInput("use_custom_team", "Use Custom Team", FALSE),
294
+ # Conditional panel for team selection
295
+ conditionalPanel(
296
+ condition = "input.use_custom_team == true",
297
+ selectInput(
298
+ inputId = "team",
299
+ label = "Select Team",
300
+ choices = c(
301
+ # Regular teams (sorted alphabetically)
302
+ "Angels" = "LAA",
303
+ "Astros" = "HOU",
304
+ "Athletics" = "OAK",
305
+ "Blue Jays" = "TOR",
306
+ "Braves" = "ATL",
307
+ "Brewers" = "MIL",
308
+ "Cardinals" = "STL",
309
+ "Cubs" = "CHC",
310
+ "D-backs" = "ARI",
311
+ "Dodgers" = "LAD",
312
+ "Giants" = "SF",
313
+ "Guardians" = "CLE",
314
+ "Mariners" = "SEA",
315
+ "Marlins" = "MIA",
316
+ "Mets" = "NYM",
317
+ "Nationals" = "WSH",
318
+ "Orioles" = "BAL",
319
+ "Padres" = "SD",
320
+ "Phillies" = "PHI",
321
+ "Pirates" = "PIT",
322
+ "Rangers" = "TEX",
323
+ "Rays" = "TB",
324
+ "Red Sox" = "BOS",
325
+ "Reds" = "CIN",
326
+ "Rockies" = "COL",
327
+ "Royals" = "KC",
328
+ "Tigers" = "DET",
329
+ "Twins" = "MIN",
330
+ "White Sox" = "CHW",
331
+ "Yankees" = "NYY",
332
+ # MLB option at the top
333
+ "MLB" = "MLB"
334
+ ),
335
+ selected = "MLB"
336
  )
337
+ ),
338
+ ),
339
+
340
+ mainPanel(
341
+ plotOutput("statsPlot", height = "1000px", width = "1000px")
342
+ )
343
+ )
344
+ )
345
+
346
+ # Server logic
347
+ server <- function(input, output,session) {
348
+
349
+ observeEvent(c(input$szn,input$level), {
350
+ # Filter data based on selected season
351
+ filtered_data <- MLBC[MLBC$season == input$szn & MLBC$level == input$level,]
352
+
353
+ updateSelectInput(session,
354
+ inputId = "player",
355
+ choices = unique(filtered_data$`Batter Name`))
356
+ })
357
+ # Create reactive value to store team
358
+ team_value <- reactiveVal("MLB")
359
+ position_value <- reactiveVal("")
360
+ # Watch for player or season changes to update team
361
+ observeEvent(c(input$player, input$szn), {
362
+ if (!input$use_custom_team && !is.null(input$player)) {
363
+
364
+ player_id <- MLBC %>%
365
+ filter(`Batter Name` == input$player) %>%
366
+ pull(`Batter ID`) %>%
367
+ unique() %>%
368
+ first()
369
+
370
+ if (!is.null(player_id)) {
371
+ player_info <- get_player_info(player_id, input$szn, input$level)
372
+
373
+ team_abb <- switch(player_info$team,
374
+ "Los Angeles Angels" = "LAA",
375
+ "Houston Astros" = "HOU",
376
+ "Oakland Athletics" = "OAK",
377
+ "Toronto Blue Jays" = "TOR",
378
+ "Atlanta Braves" = "ATL",
379
+ "Milwaukee Brewers" = "MIL",
380
+ "St. Louis Cardinals" = "STL",
381
+ "Chicago Cubs" = "CHC",
382
+ "Arizona Diamondbacks" = "ARI",
383
+ "Los Angeles Dodgers" = "LAD",
384
+ "San Francisco Giants" = "SF",
385
+ "Cleveland Guardians" = "CLE",
386
+ "Seattle Mariners" = "SEA",
387
+ "Miami Marlins" = "MIA",
388
+ "New York Mets" = "NYM",
389
+ "Washington Nationals" = "WSH",
390
+ "Baltimore Orioles" = "BAL",
391
+ "San Diego Padres" = "SD",
392
+ "Philadelphia Phillies" = "PHI",
393
+ "Pittsburgh Pirates" = "PIT",
394
+ "Texas Rangers" = "TEX",
395
+ "Tampa Bay Rays" = "TB",
396
+ "Boston Red Sox" = "BOS",
397
+ "Cincinnati Reds" = "CIN",
398
+ "Colorado Rockies" = "COL",
399
+ "Kansas City Royals" = "KC",
400
+ "Detroit Tigers" = "DET",
401
+ "Minnesota Twins" = "MIN",
402
+ "Chicago White Sox" = "CHW",
403
+ "New York Yankees" = "NYY",
404
+ "MLB")
405
+ if(is.na(team_abb)){
406
+ team_abb <- "MLB"
407
+ }
408
+ team_value(team_abb)
409
+ position_value(player_info$position)
410
  }
411
+ }
412
+ })
413
+
414
+ current_team <- reactive({
415
+ if (input$use_custom_team) {
416
+ return(input$team)
417
+ } else {
418
+ return(team_value())
419
+ }
420
+ })
421
+
422
+ output$statsPlot <- renderPlot({
423
+ req(position_value())
424
+ data <- data %>% filter(season == input$szn,level == input$level)
425
+
426
+ BBE <- MLBC %>%
427
+ filter(season == input$szn) %>%
428
+ filter(`Batter Name` == input$player) %>%
429
+ mutate(
430
+ BBE = case_when(description %in% c('In play, run(s)','In play, out(s)','In play, no out') ~ TRUE, TRUE ~ FALSE)
431
+ )
432
+
433
+
434
+ indv <- data %>% filter(`Batter Name` == input$player,level == input$level)
435
+ #if(indv[1,5] >= 149){
436
+ qual <- data %>% filter(BIP > 249)
437
+ data <- rbind(indv,qual)
438
+ data <- unique(data)
439
+ #}
440
+ current_data <- apply_percentile_calcs(data %>% select(-BIP)) %>%
441
+ filter(`Batter.Name` == input$player) %>%
442
+ mutate(metric = factor(metric, levels = c(
443
+ "wOBA", "wOBACON", "xwOBA", "xwOBACON",
444
+ "Avg EV", "EV90", "Max EV",
445
+ "stdev(LA)", "Barrel%",
446
+ "Z-Con%", "Z-Swing%", "O-Con%",
447
+ "Chase%", "Whiff%", "Swing%", "SwStr%"
448
+ ))) %>%
449
+ arrange(metric)
450
+ #current_data <- data
451
+ pos <- position_value()
452
 
453
+ BBE <- sum(BBE$BBE,na.rm = TRUE)
454
+
455
+ # Add Roboto Condensed font
456
+ font_add_google("Roboto Condensed", "roboto")
457
+ showtext_auto()
458
+
459
+ # Color function
460
+ current_data$color <- scales::gradient_n_pal(c("#325aa1","#90A4AE", "#D82129"))(current_data$percentile/100)
461
+
462
+ # Labels plot
463
+ labels_plot <- ggplot() +
464
+ annotate("text", x = c(10, 50, 90), y = 1,
465
+ label = c("Poor", "Average", "Great"),
466
+ color = c("#3661ad", "#90A4AE", "#DC3545"),
467
+ family = "roboto", size = 6) +
468
+ annotate("text", x = c(10, 50, 90), y = 0.5,
469
+ label = "▲",
470
+ color = c("#3661ad", "#90A4AE", "#DC3545"), size = 12) +
471
+ scale_x_continuous(limits = c(-16, 113), expand = c(0, 0)) +
472
+ scale_y_continuous(limits = c(0.5, 1.5)) +
473
+ theme_void()
474
+
475
+ # Main plot
476
+ main_plot <- ggplot(current_data, aes(y = factor(metric, levels = rev(metric)))) +
477
+ geom_tile(aes(x = 50, width = 100),
478
+ fill = "#c7dcdc", alpha = 0.3, height = 0.25) +
479
+ geom_tile(aes(x = percentile/2, width = percentile, fill = color),
480
+ height = 0.7) +
481
+ annotate("segment", x = c(10, 50, 90), xend = c(10, 50, 90),
482
+ y = 0, yend = 15.35,
483
+ color = c("white"),
484
+ linewidth = 1.5, alpha = 0.5) +
485
+ geom_segment(aes(x = -2, xend = -16,
486
+ y = as.numeric(factor(metric, levels = rev(metric))) - 0.3,
487
+ yend = as.numeric(factor(metric, levels = rev(metric))) - 0.3),
488
+ linetype = "longdash", color = "#399098", size = 1) +
489
+ geom_segment(aes(x = 102, xend = 113,
490
+ y = as.numeric(factor(metric, levels = rev(metric))) - 0.3,
491
+ yend = as.numeric(factor(metric, levels = rev(metric))) - 0.3),
492
+ linetype = "longdash", color = "#399098", size = 1) +
493
+ geom_text(aes(x = -3, label = metric),
494
+ hjust = 1, size = 6, family = "roboto") +
495
+ geom_text(aes(x = 103, label = value),
496
+ hjust = 0, size = 6, family = "roboto") +
497
+ geom_point(aes(x = percentile, color = "white", fill = color),
498
+ size = 16, shape = 21, stroke = 3) +
499
+ geom_text(aes(x = percentile, label = percentile),
500
+ size = 6, color = "white", fontface = "bold", family = "roboto") +
501
+ scale_x_continuous(limits = c(-16, 113), expand = c(0, 0)) +
502
+ scale_fill_identity() +
503
+ scale_color_identity() +
504
+ theme_minimal() +
505
+ theme(
506
+ axis.text = element_blank(),
507
+ axis.title = element_blank(),
508
+ panel.grid = element_blank(),
509
+ plot.margin = margin(t = 0, r = 0, b = -20, l = 0), # Reduced bottom margin
510
+ text = element_text(family = "roboto")
511
+ )
512
+
513
+ # Load and process team logo
514
+ if(current_team() == "MLB"){
515
+ logo_url <- "https://a.espncdn.com/combiner/i?img=/i/teamlogos/leagues/500/mlb.png?w=400&h=400&transparent=true"
516
+ } else {
517
+ logo_url <- sprintf("https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/%s.png&h=200&w=200",
518
+ current_team())
519
+ }
520
+ logo_img <- image_read(logo_url)
521
+ logo_raster <- as.raster(logo_img)
522
+
523
+
524
+ #player_url <- sprintf(paste0("https://img.mlbstatic.com/mlb-photos/image/upload/d_headshot_silo_generic.png,ar_1:1,b_auto:border,c_pad,q_auto:best/w_60/v1/people/427012/headshot/milb/current"))
525
+ player_url <- get_player_image(current_data[1,2])
526
+ player_img <- image_read(player_url)
527
+ player_raster <- as.raster(player_img)
528
+ # Create title with logo
529
+ title_grob <- textGrob(paste0(input$player, " - ", pos,
530
+ "\n BBE - ", BBE, "\n",
531
+ "Percentile Rankings - ",input$szn),
532
+ gp = gpar(fontsize = 25, fontface = "bold",
533
+ fontfamily = "roboto"))
534
+ logo_grob <- rasterGrob(logo_raster, x = 0, width = unit(.5, "npc"),hjust = 0)
535
+ player_grob <- rasterGrob(player_raster, x = 0.5, width = unit(.5, "npc"),hjust = 0)
536
+ title_with_logo <- arrangeGrob(logo_grob, title_grob,player_grob, ncol = 3,
537
+ widths = c(.25,.5,.25))
538
+ caption_grob <- textGrob("Viz by: @TimStats | tim-stats.com | Data: MLB",gp = gpar(fontsize = 15, fontface = "bold",
539
+ fontfamily = "roboto"))
540
+
541
+ # Final arrangement with logo in title
542
+ final_plot <- grid.arrange(
543
+ title_with_logo,
544
+ labels_plot,
545
+ main_plot,
546
+ caption_grob,
547
+ heights = c(0.15, 0.05, 0.75, 0.05)
548
+ )
549
+
550
+ grid.arrange(
551
+ gtable_add_padding(
552
+ final_plot,
553
+ padding = unit(c(20, 20, 20, 20), "points") # top, right, bottom, left margins
554
+ )
555
+ )
556
+ }, height = 1000, width = 1000)
557
  }
558
 
559
+ # Run the app
560
+ shinyApp(ui = ui, server = server)