Spaces:
Sleeping
Sleeping
File size: 16,709 Bytes
971fe13 b2c3307 619e86e e2a31f7 029ee24 7d5f54d 029ee24 c55707a 7d5f54d caefdd2 747c262 7e1e22e 8f589ba 2c79d05 2b9277c 7e1e22e 2c79d05 942445b 7e1e22e 942445b 7e1e22e 942445b 7e1e22e 2c79d05 7e1e22e 2c79d05 7e1e22e 2c79d05 7e1e22e 2c79d05 7e1e22e 2c79d05 7e1e22e 2c79d05 7e1e22e 2c79d05 7e1e22e 2c79d05 7e1e22e e0290c7 7e1e22e 2c79d05 942445b 7e1e22e 2c79d05 7e1e22e 2c79d05 7e1e22e 2c79d05 7e1e22e 2c79d05 942445b 7e1e22e 942445b 7e1e22e 2c79d05 7e1e22e 2c79d05 7e1e22e 2c79d05 7e1e22e 2c79d05 7e1e22e e0290c7 7e1e22e 7f6f7da 2c79d05 7e1e22e de16f26 7d5f54d 6918165 7e1e22e 971fe13 7e1e22e 2c79d05 7e1e22e e1a26c2 7e1e22e 971fe13 7e1e22e 2c79d05 2b9277c 2c79d05 971fe13 7e1e22e 2c79d05 7e1e22e 2c79d05 7e1e22e 2c79d05 7e1e22e 3cc1e57 7e1e22e 2c79d05 7e1e22e 2c79d05 7e1e22e 971fe13 7e1e22e 2c79d05 7e1e22e 2c79d05 7e1e22e 971fe13 7e1e22e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 | library(shiny)
library(dplyr)
library(ggplot2)
library(utils)
library(httr)
download_private_csv <- function(repo_id, filename) {
url <- paste0("https://huggingface.co/datasets/", repo_id, "/resolve/main/", filename)
response <- GET(url, add_headers(Authorization = paste("Bearer", Sys.getenv("GETCSV"))))
if (status_code(response) == 200) {
# Get content as text first to check if it's an LFS pointer
content_text <- content(response, "text", encoding = "UTF-8")
# Check if this is an LFS pointer (LFS files start with "version https://git-lfs.github.com/spec/")
if (grepl("^version https://git-lfs.github.com/spec/", content_text)) {
# This is an LFS file - extract the oid (hash) from the pointer
oid_line <- grep("oid sha256:", strsplit(content_text, "\n")[[1]], value = TRUE)
oid <- gsub("oid sha256:", "", oid_line)
oid <- trimws(oid)
# Construct the LFS content URL
lfs_url <- paste0("https://huggingface.co/datasets/", repo_id, "/resolve/main/.git/lfs/objects/",
substr(oid, 1, 2), "/", substr(oid, 3, 4), "/", oid)
# Get the actual content from LFS storage
lfs_response <- GET(lfs_url, add_headers(Authorization = paste("Bearer", Sys.getenv("GETCSV"))))
if (status_code(lfs_response) == 200) {
content_text <- content(lfs_response, "text", encoding = "UTF-8")
} else {
# Alternative LFS URL format
lfs_url <- paste0("https://huggingface.co/datasets/", repo_id, "/lfs/resolve/main/", filename, "?download=true")
lfs_response <- GET(lfs_url, add_headers(Authorization = paste("Bearer", Sys.getenv("GETCSV"))))
if (status_code(lfs_response) == 200) {
content_text <- content(lfs_response, "text", encoding = "UTF-8")
} else {
stop(paste("Failed to download LFS content. Status code:", status_code(lfs_response)))
}
}
}
# Process the content (whether it was LFS or regular)
con <- textConnection(content_text)
tryCatch({
data <- read.csv(con,
header = TRUE,
check.names = FALSE,
fileEncoding = "UTF-8",
stringsAsFactors = FALSE)
return(data)
}, error = function(e) {
close(con)
stop(paste("Error parsing CSV:", e$message))
}, finally = {
close(con)
})
} else {
stop(paste("Failed to download dataset. Status code:", status_code(response)))
}
}
download_private_parquet <- function(repo_id, filename) {
library(httr)
library(arrow)
# Create the direct download URL based on your example
url <- paste0("https://huggingface.co/datasets/", repo_id, "/resolve/main/", filename, "?download=true")
# Create a temporary file
temp_file <- tempfile(fileext = ".parquet")
# Download directly to file
response <- GET(
url,
add_headers(Authorization = paste("Bearer", Sys.getenv("GETCSV"))),
write_disk(temp_file, overwrite = TRUE)
)
# Check if download was successful
if (status_code(response) == 200) {
tryCatch({
# Read the parquet file
data <- read_parquet(temp_file)
file.remove(temp_file)
return(data)
}, error = function(e) {
file.remove(temp_file)
stop(paste("Error reading parquet file:", e$message))
})
} else {
file.remove(temp_file)
stop(paste("Failed to download file. Status code:", status_code(response)))
}
}
MLB26 <- download_private_parquet("TimStats/StatcastDataAll", "MLB26.parquet")
MLB26$level <- "MLB"
MLB25 <- download_private_parquet("TimStats/StatcastDataAll", "MLB25.parquet")
MLB25$level <- "MLB"
#names(ST)
MLB <- download_private_parquet("TimStats/StatcastDataAll", "MLB.parquet")
MLB$level <- "MLB"
data1 <- rbind(MLB,MLB25,MLB26)
#data1 <- read.csv("data1.csv", header = TRUE, check.names = FALSE, fileEncoding = "UTF-8")
#data1 <- data1[,2:54]
AAaveragePT <- data1 %>%
mutate(arm_angle = round(arm_angle, digits = 0)) %>%
group_by(arm_angle, phand, pitch_name) %>%
summarise(
AvgIVB = mean(IVB, na.rm = TRUE),
AvgHB = mean(HB, na.rm = TRUE),
.groups = 'drop'
)
pitch_type_lookup <- data.frame(
pitch_name = c("Changeup", "Curveball", "Cutter", "Eephus", "Forkball",
"Four-Seam Fastball", "Knuckle Ball", "Knuckle Curve",
"Screwball", "Sinker", "Slider", "Slurve", "Splitter", "Sweeper"),
pitch_abbr = c("CH", "CU", "FC", "EP", "FO", "FF", "KN", "KC",
"SC", "SI", "SL", "SV", "FS", "ST"),
stringsAsFactors = FALSE
)
pitch_colors <- c(
"FF" = "#FF4136",
"SI" = "#FF851B",
"FC" = "#FFDC00",
"CH" = "#2ECC40",
"SL" = "#0074D9",
"ST" = "#ED68ED",
"CU" = "#B10DC9",
"FS" = "#01FF70",
"KC" = "#85144b",
"SV" = "#3D9970",
"KN" = "#39CCCC",
"FO" = "#F012BE",
"EP" = "#AAAAAA",
"FA" = "#7FDBFF",
"SC" = "#FF69B4"
)
break_plot_Szn <- function(game, data1, sdate, edate) {
# Calculate pitch usage percentages
game <- game %>% filter(between(as.Date(date), sdate, edate))
total_pitches <- nrow(game)
usage_stats <- game %>%
group_by(pitch_name) %>%
summarise(
count = n(),
usage = sprintf("%.1f%%", (count/total_pitches) * 100)
)
game <- game %>%
left_join(pitch_type_lookup, by = c("pitch_name")) %>%
left_join(usage_stats, by = "pitch_name")
game <- game %>% filter(!is.na(pitch_abbr))
title <- paste0(unique(game$`Pitcher Name`)," ",sdate," to ",edate)
pitcher_hand <- unique(game$phand)
angle_degrees <- round(mean(game$arm_angle,na.rm = TRUE),digits = 1)
angle_radians <- angle_degrees * (pi / 180)
if(pitcher_hand == "L") {
leg <- c(0.08, .22)
factor <- -1
} else {
leg <- c(0.92, .22)
factor <- 1
}
x_end <- 50 * cos(angle_radians) * factor
y_end <- 50 * sin(angle_radians)
# Create the base color mapping
game_pitches <- unique(game$pitch_abbr)
used_colors <- pitch_colors[game_pitches]
# Add usage to the game data
avg_locations <- game %>%
group_by(pitch_abbr) %>%
summarize(
avg_HB = mean(HB, na.rm = TRUE),
avg_IVB = mean(IVB, na.rm = TRUE),
usage = first(usage) # Keep the usage info
)
# Create labels with percentages
legend_labels <- paste0(names(used_colors), " (",
avg_locations$usage[match(names(used_colors), avg_locations$pitch_abbr)], ")")
# Create the color scale with usage labels
fill_values <- used_colors
names(fill_values) <- legend_labels
arm_angle_data <- data1 %>%
filter(!is.na(arm_angle), !is.na(phand), !is.na(pitch_name)) %>%
filter(abs(round(arm_angle) - angle_degrees) <= 2, phand == pitcher_hand) %>%
left_join(pitch_type_lookup, by = c("pitch_name")) %>%
filter(!is.na(pitch_abbr)) %>%
filter(pitch_abbr %in% game_pitches)
ggplot(game, aes(x = HB, y = IVB)) +
geom_vline(xintercept = 0, color = "lightblue", linewidth = 1, linetype = 4) +
geom_hline(yintercept = 0, color = "lightblue", linewidth = 1, linetype = 4) +
# Ellipses
stat_ellipse(
data = arm_angle_data,
aes(fill = paste0(pitch_abbr, " (",
avg_locations$usage[match(pitch_abbr, avg_locations$pitch_abbr)], ")")),
geom = "polygon",
alpha = 0.2,
level = 0.68,
show.legend = FALSE
) +
# Average points
geom_point(
data = avg_locations,
aes(x = avg_HB, y = avg_IVB,
fill = paste0(pitch_abbr, " (", usage, ")")),
color = "black",
size = 6,
stroke = .5,
shape = 21
) +
# Arm angle line
geom_segment(x = 0, y = 0, xend = x_end, yend = y_end,
color = "red", linewidth = 1, linetype = 5) +
scale_fill_manual(values = fill_values) +
labs(
x = "Horizontal Break (in)",
y = "Induced Vertical Break (in)",
title = title,
subtitle = paste0("Arm Angle: ", angle_degrees, "\u00b0"),
caption = "Data: MLB | Viz: @TimStats | tim-stats.com\nEllipses show average movement for same-handed pitchers at similar arm angles"
) +
xlim(-25, 25) +
ylim(-25, 25) +
theme_minimal() +
theme(
legend.position = leg,
plot.title = element_text(hjust = 0.5, face = "bold", color = "white"),
plot.subtitle = element_text(hjust = 0.5, face = "italic", color = "white"),
aspect.ratio = 1,
plot.background = element_rect(fill = "#333333", color = NA),
panel.background = element_rect(fill = "#333333", color = NA),
axis.text = element_text(color = "white"),
axis.title = element_text(color = "white"),
legend.background = element_rect(fill = "#333333"),
legend.text = element_text(color = "white"),
legend.title = element_blank(),
plot.margin = margin(10, 5, 10, 5),
axis.line = element_blank(),
axis.ticks = element_line(color = "white"),
panel.grid = element_blank(),
legend.key = element_blank(),
plot.caption = element_text(
color = "white",
hjust = 0.5
),
panel.border = element_blank()
)
}
break_plot_tot <- function(game, data1, sdate, edate) {
# Calculate pitch usage percentages
game <- game %>% filter(between(as.Date(date), sdate, edate))
total_pitches <- nrow(game)
usage_stats <- game %>%
group_by(pitch_name) %>%
summarise(
count = n(),
usage = sprintf("%.1f%%", (count/total_pitches) * 100)
)
game <- game %>%
left_join(pitch_type_lookup, by = c("pitch_name")) %>%
left_join(usage_stats, by = "pitch_name")
game <- game %>% filter(!is.na(pitch_abbr))
title <- paste0(unique(game$`Pitcher Name`)," ",sdate," to ",edate)
pitcher_hand <- unique(game$phand)
angle_degrees <- round(mean(game$arm_angle,na.rm = TRUE),digits = 1)
angle_radians <- angle_degrees * (pi / 180)
if(pitcher_hand == "L") {
leg <- c(0.08, .22)
factor <- -1
} else {
leg <- c(0.92, .22)
factor <- 1
}
x_end <- 50 * cos(angle_radians) * factor
y_end <- 50 * sin(angle_radians)
# Create the base color mapping
game_pitches <- unique(game$pitch_abbr)
used_colors <- pitch_colors[game_pitches]
# Add usage to the game data
avg_locations <- game %>%
group_by(pitch_abbr) %>%
summarize(
avg_HB = mean(HB, na.rm = TRUE),
avg_IVB = mean(IVB, na.rm = TRUE),
usage = first(usage) # Keep the usage info
)
# Create labels with percentages
legend_labels <- paste0(names(used_colors), " (",
avg_locations$usage[match(names(used_colors), avg_locations$pitch_abbr)], ")")
# Create the color scale with usage labels
fill_values <- used_colors
names(fill_values) <- legend_labels
arm_angle_data <- data1 %>%
filter(!is.na(arm_angle), !is.na(phand), !is.na(pitch_name)) %>%
filter(abs(round(arm_angle) - angle_degrees) <= 2, phand == pitcher_hand) %>%
left_join(pitch_type_lookup, by = c("pitch_name")) %>%
filter(!is.na(pitch_abbr)) %>%
filter(pitch_abbr %in% game_pitches)
ggplot(game, aes(x = HB, y = IVB)) +
geom_vline(xintercept = 0, color = "lightblue", linewidth = 1, linetype = 4) +
geom_hline(yintercept = 0, color = "lightblue", linewidth = 1, linetype = 4) +
# Ellipses
stat_ellipse(
data = arm_angle_data,
aes(fill = paste0(pitch_abbr, " (",
avg_locations$usage[match(pitch_abbr, avg_locations$pitch_abbr)], ")")),
geom = "polygon",
alpha = 0.2,
level = 0.68,
show.legend = FALSE
) +
# Individual points
geom_point(
aes(fill = paste0(pitch_abbr, " (", usage, ")")),
color = "#c6c6c6",
size = 3,
stroke = .5,
shape = 21
) +
# Average points
geom_point(
data = avg_locations,
aes(x = avg_HB, y = avg_IVB,
fill = paste0(pitch_abbr, " (", usage, ")")),
color = "black",
size = 6,
stroke = .5,
shape = 21
) +
# Arm angle line
geom_segment(x = 0, y = 0, xend = x_end, yend = y_end,
color = "red", linewidth = 1, linetype = 5) +
scale_fill_manual(values = fill_values) +
labs(
x = "Horizontal Break (in)",
y = "Induced Vertical Break (in)",
title = title,
subtitle = paste0("Arm Angle: ", angle_degrees, "\u00b0"),
caption = "Data: MLB | Viz: @TimStats | tim-stats.com\nEllipses show average movement for same-handed pitchers at similar arm angles"
) +
xlim(-25, 25) +
ylim(-25, 25) +
theme_minimal() +
theme(
legend.position = leg,
plot.title = element_text(hjust = 0.5, face = "bold", color = "white"),
plot.subtitle = element_text(hjust = 0.5, face = "italic", color = "white"),
aspect.ratio = 1,
plot.background = element_rect(fill = "#333333", color = NA),
panel.background = element_rect(fill = "#333333", color = NA),
axis.text = element_text(color = "white"),
axis.title = element_text(color = "white"),
legend.background = element_rect(fill = "#333333"),
legend.text = element_text(color = "white"),
legend.title = element_blank(),
plot.margin = margin(10, 5, 10, 5),
axis.line = element_blank(),
axis.ticks = element_line(color = "white"),
panel.grid = element_blank(),
legend.key = element_blank(),
plot.caption = element_text(
color = "white",
hjust = 0.5
),
panel.border = element_blank()
)
}
ui <- fluidPage(
# Application title
titlePanel("2020-2025 MLB Pitch Plots"),
sidebarLayout(
sidebarPanel(
width = 3,
selectInput("player", "Select Player:", choices = unique(data1$`Pitcher Name`),
width = "100%"),
dateRangeInput("date1", "Dates: (Be wary of multi year plots as arm angles may vary over years)",
start = "2026-03-18",
end = Sys.Date(),
width = "100%"),
radioButtons("type", "Plot Type",
choices = c("Season Average","All Pitches")),
actionButton("submit", "Update Plot",
class = "btn btn-primary btn-block",
style = "margin-bottom: 10px"),
downloadButton("download", "Download Plot",
class = "btn btn-success btn-block")
),
mainPanel(
width = 9,
plotOutput("Plot",height = "1200px",width = "100%")
)
)
)
# Define server
server <- function(input, output, session) {
# Create a reactive value to store current plot settings
plotSettings <- reactiveVal(list(
player = NULL,
type = "Season Average",
dates = c(as.Date("2024-03-20"), as.Date("2024-10-01"))
))
# Update settings only when submit is clicked
observeEvent(input$submit, {
plotSettings(list(
player = input$player,
type = input$type,
dates = c(input$date1[1], input$date1[2])
))
})
output$Plot <- renderPlot({
settings <- plotSettings()
req(settings$player) # Wait until we have a player selected
game <- data1 %>%
filter(`Pitcher Name` == settings$player)
if(nrow(game) == 0) {
return(ggplot() +
annotate("text", x = 0.5, y = 0.5,
label = "No data available for selected date range",
color = "white") +
theme_void() +
theme(plot.background = element_rect(fill = "#333333", color = NA)))
}
if(settings$type == "Season Average"){
break_plot_Szn(game, data1, settings$dates[1], settings$dates[2])
} else{
break_plot_tot(game, data1, settings$dates[1], settings$dates[2])
}
}, width = 750, height = 750, bg = "#333333")
output$download <- downloadHandler(
filename = function() {
settings <- plotSettings()
paste0(
gsub(" ", "_", settings$player), "_",
format(settings$dates[1], "%Y%m%d"), "_to_",
format(settings$dates[2], "%Y%m%d"), ".png"
)
},
content = function(file) {
settings <- plotSettings()
game <- data1 %>%
filter(`Pitcher Name` == settings$player)
plot <- if(settings$type == "Season Average"){
break_plot_Szn(game, data1, settings$dates[1], settings$dates[2])
} else{
break_plot_tot(game, data1, settings$dates[1], settings$dates[2])
}
ggsave(file,
plot = plot,
width = 10,
height = 10,
dpi = 300,
bg = "#333333")
}
)
}
shinyApp(ui = ui, server = server) |