File size: 31,260 Bytes
44bda9d 0b7aa7f 44bda9d ec48d0c 44bda9d ec48d0c 44bda9d ec48d0c 44bda9d ec48d0c 44bda9d ec48d0c 44bda9d a774a26 44bda9d ec48d0c 44bda9d ae2dabb 4278763 57baf22 ae2dabb 44bda9d f716003 44bda9d a8b7eaa f716003 6850181 44bda9d fcb7c74 |
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 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 |
import polars as pl
import numpy as np
import pandas as pd
import api_scraper
scrape = api_scraper.MLB_Scrape()
from functions import df_update
from functions import pitch_summary_functions
update = df_update.df_update()
from stuff_model import feature_engineering as fe
from stuff_model import stuff_apply
import requests
import joblib
from matplotlib.gridspec import GridSpec
from shiny import App, reactive, ui, render
from shiny.ui import h2, tags
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import seaborn as sns
from functions.pitch_summary_functions import *
from shiny import App, reactive, ui, render
from shiny.ui import h2, tags
# from functions.PitchPlotFunctions import *
import functions.PitchPlotFunctions as ppf
import matplotlib
ploter = ppf.PitchPlotFunctions()
from shiny.plotutils import brushed_points
# from pytabulator import TableOptions, Tabulator, output_tabulator, render_tabulator, theme
# theme.tabulator_site()
colour_palette = ['#FFB000','#648FFF','#785EF0',
'#DC267F','#FE6100','#3D1EB2','#894D80','#16AA02','#B5592B','#A3C1ED']
cmap_sum = mcolors.LinearSegmentedColormap.from_list("", ['#648FFF', '#FFFFFF', '#FFB000'])
year_list = [2017,2018,2019,2020,2021,2022,2023,2024]
level_dict = {'1':'MLB',
'11':'AAA',
'12':'AA',
'13':'A+',
'14':'A',
'17':'AFL',
'22':'College',
'21':'Prospects',
'51':'International' }
function_dict={
'velocity_kdes':'Velocity Distributions',
'break_plot':'Pitch Movement',
'tj_stuff_roling':'Rolling tjStuff+ by Pitch',
'tj_stuff_roling_game':'Rolling tjStuff+ by Game',
'location_plot_lhb':'Locations vs LHB',
'location_plot_rhb':'Locations vs RHB',
}
split_dict = {'all':'All',
'left':'LHH',
'right':'RHH'}
split_dict_hand = {'all':['L','R'],
'left':['L'],
'right':['R']}
### PITCH COLOURS ###
# Dictionary to map pitch types to their corresponding colors and names
pitch_colours = {
## Fastballs ##
'FF': {'colour': '#FF007D', 'name': '4-Seam Fastball'},
'FA': {'colour': '#FF007D', 'name': 'Fastball'},
'SI': {'colour': '#98165D', 'name': 'Sinker'},
'FC': {'colour': '#BE5FA0', 'name': 'Cutter'},
## Offspeed ##
'CH': {'colour': '#F79E70', 'name': 'Changeup'},
'FS': {'colour': '#FE6100', 'name': 'Splitter'},
'SC': {'colour': '#F08223', 'name': 'Screwball'},
'FO': {'colour': '#FFB000', 'name': 'Forkball'},
## Sliders ##
'SL': {'colour': '#67E18D', 'name': 'Slider'},
'ST': {'colour': '#1BB999', 'name': 'Sweeper'},
'SV': {'colour': '#376748', 'name': 'Slurve'},
## Curveballs ##
'KC': {'colour': '#311D8B', 'name': 'Knuckle Curve'},
'CU': {'colour': '#3025CE', 'name': 'Curveball'},
'CS': {'colour': '#274BFC', 'name': 'Slow Curve'},
'EP': {'colour': '#648FFF', 'name': 'Eephus'},
## Others ##
'KN': {'colour': '#867A08', 'name': 'Knuckleball'},
'KN': {'colour': '#867A08', 'name': 'Knuckle Ball'},
'PO': {'colour': '#472C30', 'name': 'Pitch Out'},
'UN': {'colour': '#9C8975', 'name': 'Unknown'},
}
# Create dictionaries for pitch types and their attributes
dict_colour = {key: value['colour'] for key, value in pitch_colours.items()}
dict_pitch = {key: value['name'] for key, value in pitch_colours.items()}
dict_pitch_desc_type = {value['name']: key for key, value in pitch_colours.items()}
dict_pitch_desc_type.update({'Four-Seam Fastball':'FF'})
dict_pitch_desc_type.update({'All':'All'})
dict_pitch_name = {value['name']: value['colour'] for key, value in pitch_colours.items()}
dict_pitch_name.update({'Four-Seam Fastball':'#FF007D'})
dict_pitch_name.update({'4-Seam':'#FF007D'})
from shiny import App, reactive, ui, render
from shiny.ui import h2, tags
# Define the UI layout for the app
app_ui = ui.page_fluid(
ui.layout_sidebar(
ui.panel_sidebar(
# Row for selecting season and level
ui.row(
ui.column(6, ui.input_select('year_input', 'Select Season', year_list, selected=2024)),
ui.column(6, ui.input_select('level_input', 'Select Level', level_dict))
),
# Row for the action button to get player list
ui.row(ui.input_action_button("player_button", "Get Player List", class_="btn-primary")),
# Row for selecting the player
ui.row(ui.column(12, ui.output_ui('player_select_ui', 'Select Player'))),
# Row for selecting the date range
ui.row(ui.column(12, ui.output_ui('date_id', 'Select Date'))),
ui.row(
ui.column(6, ui.input_select('split_id', 'Select Split', split_dict, multiple=False)),
),
# Row for the action button to generate plot
ui.row(ui.input_action_button("generate_plot", "Generate Plot", class_="btn-primary")),
ui.row(ui.input_action_button("generate_table", "Generate Table", class_="btn-warning")),
),
ui.panel_main(
# ui.navset_tab(
# Tab for game summary plot
# ui.nav(
# "Pitching Summary",
ui.card(
{"style": "width: 870px;"},
ui.head_content(
ui.tags.script(src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.8.5/d3.min.js"),
ui.tags.script(src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"),
ui.tags.script("""
async function downloadSVG() {
const content = document.getElementById('capture-section');
// Create a new SVG element
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
const bbox = content.getBoundingClientRect();
// Set SVG attributes
svg.setAttribute('width', bbox.width);
svg.setAttribute('height', bbox.height);
svg.setAttribute('viewBox', `0 0 ${bbox.width} ${bbox.height}`);
// Create foreignObject to contain HTML content
const foreignObject = document.createElementNS('http://www.w3.org/2000/svg', 'foreignObject');
foreignObject.setAttribute('width', '100%');
foreignObject.setAttribute('height', '100%');
foreignObject.setAttribute('x', '0');
foreignObject.setAttribute('y', '0');
// Clone the content and its styles
const clonedContent = content.cloneNode(true);
// Add necessary style context
const style = document.createElement('style');
Array.from(document.styleSheets).forEach(sheet => {
try {
Array.from(sheet.cssRules).forEach(rule => {
style.innerHTML += rule.cssText + '\\n';
});
} catch (e) {
console.warn('Could not access stylesheet rules');
}
});
// Create a wrapper div to hold styles and content
const wrapper = document.createElement('div');
wrapper.appendChild(style);
wrapper.appendChild(clonedContent);
foreignObject.appendChild(wrapper);
svg.appendChild(foreignObject);
// Convert to SVG string with XML declaration and DTD
const svgString = new XMLSerializer().serializeToString(svg);
const svgBlob = new Blob([
'<?xml version="1.0" standalone="no"?>\\n',
'<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\\n',
svgString
], {type: 'image/svg+xml;charset=utf-8'});
// Create and trigger download
const url = URL.createObjectURL(svgBlob);
const link = document.createElement('a');
link.href = url;
link.download = 'plot_and_table.svg';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
}
async function downloadPNG() {
const content = document.getElementById('capture-section');
try {
// Create a wrapper div with margins
const wrapper = document.createElement('div');
wrapper.style.padding = '20px';
wrapper.style.backgroundColor = 'white';
// Clone the content
const clonedContent = content.cloneNode(true);
wrapper.appendChild(clonedContent);
// Add wrapper to document temporarily
document.body.appendChild(wrapper);
const canvas = await html2canvas(wrapper, {
backgroundColor: 'white',
scale: 2,
useCORS: true,
logging: false,
width: content.offsetWidth + 40, // Add padding width
height: content.offsetHeight + 40 // Add padding height
});
// Remove temporary wrapper
document.body.removeChild(wrapper);
// Convert canvas to blob
canvas.toBlob(function(blob) {
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'plot_and_table.png';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
}, 'image/png');
} catch (error) {
console.error('Error generating PNG:', error);
}
}
$(document).on('click', '#capture_svg_btn', function() {
downloadSVG();
});
$(document).on('click', '#capture_png_btn', function() {
downloadPNG();
});
""")
),
ui.output_text("status"),
ui.div(
{
"id": "capture-section",
"style": "background-color: white; padding: 0; margin-left: 20px; margin-right: 20px; margin-top: 20px; margin-bottom: 20px;"
},
# Plot section with relative positioning for brush
ui.div(
{"style": "position: relative;"},
ui.output_ui("plot_ui")
),
# Table section
ui.div(
{"style": "margin-top: 20px;"},
ui.row(ui.tags.b("Pitches in Selection"), ui.output_table("in_brush")),
),
ui.div({"style": "height: 20px;"})
),
ui.div(
{"style": "display: flex; gap: 10px;"},
ui.input_action_button("capture_svg_btn", "Save as SVG", class_="btn-primary"),
ui.input_action_button("capture_png_btn", "Save as PNG", class_="btn-success"),
),
)
# ),
# )
)
)
)
def server(input, output, session):
@reactive.calc
@reactive.event(input.pitcher_id, input.date_id,input.split_id)
def cached_data():
year_input = int(input.year_input())
sport_id = int(input.level_input())
player_input = int(input.pitcher_id())
start_date = str(input.date_id()[0])
end_date = str(input.date_id()[1])
# Simulate an expensive data operation
game_list = scrape.get_player_games_list(sport_id = sport_id,
season = year_input,
player_id = player_input,
start_date = start_date,
end_date = end_date)
data_list = scrape.get_data(game_list_input = game_list[:])
df = (stuff_apply.stuff_apply(fe.feature_engineering(update.update(scrape.get_data_df(data_list = data_list).filter(
(pl.col("pitcher_id") == player_input)&
(pl.col("is_pitch") == True)&
(pl.col('batter_hand').is_in(split_dict_hand[input.split_id()]))
)))).with_columns(
pl.col('pitch_type').count().over('pitch_type').alias('pitch_count')
))
df = df.with_columns(
prop_percent=(pl.col('is_pitch') / pl.col('is_pitch').sum()).over("pitch_type"),
prop=pl.col('is_pitch').sum().over("pitch_type")
)
return df
@render.ui
@reactive.event(input.player_button, input.level_input,input.year_input, ignore_none=False)
def player_select_ui():
# Get the list of pitchers for the selected level and season
df_pitcher_info = scrape.get_players(sport_id=int(input.level_input()), season=int(input.year_input())).filter(
pl.col("position").is_in(['P'])).sort("name")
# Create a dictionary of pitcher IDs and names
pitcher_dict = dict(zip(df_pitcher_info['player_id'], df_pitcher_info['name']))
# Return a select input for choosing a pitcher
return ui.input_select("pitcher_id", "Select Pitcher", pitcher_dict, selectize=True)
@render.ui
@reactive.event(input.player_button,input.pitcher_id,input.year_input, ignore_none=False)
def date_id():
# Create a date range input for selecting the date range within the selected year
return ui.input_date_range("date_id", "Select Date Range",
start=f"{int(input.year_input())}-01-01",
end=f"{int(input.year_input())}-03-31",
min=f"{int(input.year_input())}-01-01",
max=f"{int(input.year_input())}-12-31")
@output
@render.text
def status():
# Only show status when generating
if input.generate == 0:
return ""
return ""
@render.ui
@reactive.event(input.generate_plot)
def plot_ui():
brush_opts_kwargs = {
"direction": 'xy',
"delay": 60,
"delay_type": "throttle",
"clip": True, # This helps constrain the brush to the plot area
"fill": "#00000033", # Optional: sets a semi-transparent fill
"stroke": "#000000", # Resets brush when new data is loaded
}
return ui.output_plot('plot',
width='800px',
height='800px',
brush=ui.brush_opts(**brush_opts_kwargs))
@render.table
@reactive.event(input.plot_brush, input.generate_table) # Note: changed to match the brush ID
def in_brush():
# if input.plot_brush() is None: # Note: changed to match the brush ID
# return None
brushed_df = pl.DataFrame(brushed_points(
cached_data().to_pandas(),
input.plot_brush(),
xvar="hb",
yvar="ivb",
all_rows=False
))
brushed_df_final = (((brushed_df.group_by(['pitcher_id', 'pitch_description'])
.agg([
pl.col('is_pitch').drop_nans().count().alias('pitches'),
pl.col('start_speed').drop_nans().mean().round(1).alias('start_speed'),
pl.col('vb').drop_nans().mean().round(1).alias('vb'),
pl.col('ivb').drop_nans().mean().round(1).alias('ivb'),
pl.col('hb').drop_nans().mean().round(1).alias('hb'),
pl.col('spin_rate').drop_nans().mean().round(0).alias('spin_rate'),
pl.col('x0').drop_nans().mean().round(1).alias('x0'),
pl.col('z0').drop_nans().mean().round(1).alias('z0'),
pl.col('tj_stuff_plus').drop_nans().mean().round(0).alias('tj_stuff_plus'),
])
.with_columns(
(pl.col('pitches') / pl.col('pitches').sum().over('pitcher_id'))
# .round(1)
# .map_elements(lambda x: f"{x}%", return_dtype=pl.Utf8) # Properly append "%"
.alias('proportion')
)
)).sort('proportion', descending=True).
select(["pitch_description", "pitches", "proportion", "start_speed", "ivb", "hb",
"spin_rate", "x0", "z0",'tj_stuff_plus'])
.with_columns(
pl.when(pl.col("pitch_description") == "Four-Seam Fastball")
.then(pl.lit("4-Seam"))
.otherwise(pl.col("pitch_description"))
.alias("pitch_description")
)
.rename({
'pitch_description': 'Pitch Type',
'pitches': 'Pitches',
'proportion': 'Prop',
'start_speed': 'Velo',
'ivb': 'iVB',
'hb': 'HB',
'spin_rate': 'Spin',
'x0': 'hRel',
'z0': 'vRel',
'tj_stuff_plus': 'tjStuff+'
}))
# brushed_df_final = brushed_df_final
# print(brushed_df_final)
def change_font(val):
if val == "Cutter":
return "color: red; font-weight: bold;"
else:
''
return "font-weight: bold;"
df_brush_style = (brushed_df_final.to_pandas().style.set_precision(1)
.set_properties(**{'border': '3 px'},overwrite=False).set_table_styles([{
'selector': 'caption',
'props': [
('color', ''),
('fontname', 'Century Gothic'),
('font-size', '16px'),
('font-style', 'italic'),
('font-weight', ''),
('text-align', 'centre'),
]
},{'selector' :'th', 'props':[('font-size', '16px'),('text-align', 'center'),('Height','px'),('color','black'),('border', '1px black solid !important')]},{'selector' :'td', 'props':[('text-align', 'center'),('font-size', '16px'),('color','black')]}],overwrite=False)
.set_properties(**{'background-color':'White','index':'White','min-width':'72px'},overwrite=False)
.set_table_styles([{'selector': 'th:first-child', 'props': [('background-color', 'white')]}],overwrite=False)
.set_table_styles([{'selector': 'tr:first-child', 'props': [('background-color', 'white')]}],overwrite=False)
.set_table_styles([{'selector': 'tr', 'props': [('line-height', '20px')]}],overwrite=False)
.set_properties(**{'Height': '8px'},**{'text-align': 'center'},overwrite=False)
.hide_index()
.set_properties(**{'border': '1px black solid !important'})
.format('{:.0%}',subset=(brushed_df_final.columns[2]))
.format('{:.0f}',subset=(brushed_df_final.columns[6]))
.format('{:.0f}',subset=(brushed_df_final.columns[-1]))
.set_properties(subset=brushed_df_final.columns, **{'height': '30px'})
.set_table_styles([{'selector': 'thead th', 'props': [('height', '30px')]}], overwrite=False)
# .set_table_styles([{'selector': 'table', 'props': [('width', '100px')]}], overwrite=False)
.set_table_styles([{'selector': 'thead th:nth-child(1)', 'props': [('min-width', '125px')]}], overwrite=False)
.set_table_styles([{'selector': 'thead th:nth-child(2)', 'props': [('min-width', '40px')]}], overwrite=False)
.set_table_styles([{'selector': 'thead th:nth-child(3)', 'props': [('min-width', '40px')]}], overwrite=False)
.set_table_styles([{'selector': 'thead th:nth-child(4)', 'props': [('min-width', '40px')]}], overwrite=False)
.set_table_styles([{'selector': 'thead th:nth-child(5)', 'props': [('min-width', '40px')]}], overwrite=False)
.set_table_styles([{'selector': 'thead th:nth-child(6)', 'props': [('min-width', '40px')]}], overwrite=False)
.set_table_styles([{'selector': 'thead th:nth-child(7)', 'props': [('min-width', '40px')]}], overwrite=False)
.set_table_styles([{'selector': 'thead th:nth-child(8)', 'props': [('min-width', '40px')]}], overwrite=False)
.background_gradient(cmap=cmap_sum,subset = (brushed_df_final.columns[-1]),vmin=80,vmax=120)
.applymap(lambda x: f'background-color: {dict_pitch_name.get(x, "")}', subset=['Pitch Type'])
)
return df_brush_style
# return Tabulator(
# brushed_df.to_pandas(),
# table_options=TableOptions(
# height=800,
# resizable_column_fit=True,
# )
# )
# return brushed_points(
# ((brushed_df.group_by(['pitcher_id', 'pitch_description'])
# .agg([
# pl.col('is_pitch').drop_nans().count().alias('pitches'),
# pl.col('start_speed').drop_nans().mean().round(1).alias('start_speed'),
# pl.col('vb').drop_nans().mean().round(1).alias('vb'),
# pl.col('ivb').drop_nans().mean().round(1).alias('ivb'),
# pl.col('hb').drop_nans().mean().round(1).alias('hb'),
# pl.col('spin_rate').drop_nans().mean().round(0).alias('spin_rate'),
# pl.col('x0').drop_nans().mean().round(1).alias('x0'),
# pl.col('z0').drop_nans().mean().round(1).alias('z0'),
# pl.col('tj_stuff_plus').drop_nans().mean().round(0).alias('tj_stuff_plus'),
# ])
# .with_columns(
# (pl.col('pitches') / pl.col('pitches').sum().over('pitcher_id') * 100)
# .round(1)
# .map_elements(lambda x: f"{x}%", return_dtype=pl.Utf8) # Properly append "%"
# .alias('proportion')
# )
# )).sort('proportion', descending=True).
# select(["pitch_description", "pitches", "proportion", "start_speed", "ivb", "hb",
# "spin_rate", "x0", "z0",'tj_stuff_plus'])
# .rename({
# 'pitch_description': 'Pitch Type',
# 'pitches': 'Pitches',
# 'proportion': 'Proportion',
# 'start_speed': 'Velocity',
# 'ivb': 'iVB',
# 'hb': 'HB',
# 'spin_rate': 'Spin Rate',
# 'x0': 'hRel',
# 'z0': 'vRel',
# 'tj_stuff_plus': 'tjStuff+'
# }).to_pandas(),
# input.plot_brush(), # Note: changed to match the brush ID
# xvar="HB", # Replace "x" with your actual x-axis column name
# yvar="iVB", # Replace "y" with your actual y-axis column name
# all_rows=False
# )
# return brushed_points(
# ((cached_data().group_by(['pitcher_id', 'pitch_description'])
# .agg([
# pl.col('is_pitch').drop_nans().count().alias('pitches'),
# pl.col('start_speed').drop_nans().mean().round(1).alias('start_speed'),
# pl.col('vb').drop_nans().mean().round(1).alias('vb'),
# pl.col('ivb').drop_nans().mean().round(1).alias('ivb'),
# pl.col('hb').drop_nans().mean().round(1).alias('hb'),
# pl.col('spin_rate').drop_nans().mean().round(0).alias('spin_rate'),
# pl.col('x0').drop_nans().mean().round(1).alias('x0'),
# pl.col('z0').drop_nans().mean().round(1).alias('z0'),
# pl.col('tj_stuff_plus').drop_nans().mean().round(0).alias('tj_stuff_plus'),
# ])
# .with_columns(
# (pl.col('pitches') / pl.col('pitches').sum().over('pitcher_id') * 100)
# .round(1)
# .map_elements(lambda x: f"{x}%", return_dtype=pl.Utf8) # Properly append "%"
# .alias('proportion')
# )
# )).sort('proportion', descending=True).
# select(["pitch_description", "pitches", "proportion", "start_speed", "ivb", "hb",
# "spin_rate", "x0", "z0",'tj_stuff_plus'])
# .rename({
# 'pitch_description': 'Pitch Type',
# 'pitches': 'Pitches',
# 'proportion': 'Prop',
# 'start_speed': 'Velocity',
# 'ivb': 'iVB',
# 'hb': 'HB',
# 'spin_rate': 'Spin Rate',
# 'x0': 'hRel',
# 'z0': 'vRel',
# 'tj_stuff_plus': 'tjStuff+'
# }).to_pandas(),
# input.plot_brush(), # Note: changed to match the brush ID
# xvar="HB", # Replace "x" with your actual x-axis column name
# yvar="iVB", # Replace "y" with your actual y-axis column name
# all_rows=False
# )
# @output
@render.plot
@reactive.event(input.generate_plot)
def plot():
# Show progress/loading notification
with ui.Progress(min=0, max=1) as p:
p.set(message="Generating plot", detail="This may take a while...")
p.set(0.3, "Gathering data...")
year_input = int(input.year_input())
sport_id = int(input.level_input())
player_input = int(input.pitcher_id())
start_date = str(input.date_id()[0])
end_date = str(input.date_id()[1])
print(year_input, sport_id, player_input, start_date, end_date)
df = cached_data()
df = df.clone()
p.set(0.6, "Creating plot...")
# fig, ax = plt.subplots(figsize=(8, 8))
ploter.final_plot(
df=df,
pitcher_id=player_input,
plot_picker='short_form_movement',#plot_picker,
sport_id=sport_id)
# # Adjust the plot layout after creation
# plt.subplots_adjust(
# top=0.95, # Reduce top margin
# bottom=0.1, # Increase bottom margin
# left=0.1, # Increase left margin
# right=0.95 # Reduce right margin
# )
# #plt.rcParams["figure.figsize"] = [10,10]
# fig = plt.figure(figsize=(26,26))
# plt.rcParams.update({'figure.autolayout': True})
# fig.set_facecolor('white')
# sns.set_theme(style="whitegrid", palette=colour_palette)
# print('this is the one plot')
# gs = gridspec.GridSpec(6, 8,
# height_ratios=[5,20,12,36,36,7],
# width_ratios=[4,18,18,18,18,18,18,4])
# gs.update(hspace=0.2, wspace=0.5)
# # Define the positions of each subplot in the grid
# ax_headshot = fig.add_subplot(gs[1,1:3])
# ax_bio = fig.add_subplot(gs[1,3:5])
# ax_logo = fig.add_subplot(gs[1,5:7])
# ax_season_table = fig.add_subplot(gs[2,1:7])
# ax_plot_1 = fig.add_subplot(gs[3,1:3])
# ax_plot_2 = fig.add_subplot(gs[3,3:5])
# ax_plot_3 = fig.add_subplot(gs[3,5:7])
# ax_table = fig.add_subplot(gs[4,1:7])
# ax_footer = fig.add_subplot(gs[-1,1:7])
# ax_header = fig.add_subplot(gs[0,1:7])
# ax_left = fig.add_subplot(gs[:,0])
# ax_right = fig.add_subplot(gs[:,-1])
# # Hide axes for footer, header, left, and right
# ax_footer.axis('off')
# ax_header.axis('off')
# ax_left.axis('off')
# ax_right.axis('off')
# sns.set_theme(style="whitegrid", palette=colour_palette)
# fig.set_facecolor('white')
# df_teams = scrape.get_teams()
# player_headshot(player_input=player_input, ax=ax_headshot,sport_id=sport_id,season=year_input)
# player_bio(pitcher_id=player_input, ax=ax_bio,sport_id=sport_id,year_input=year_input)
# plot_logo(pitcher_id=player_input, ax=ax_logo, df_team=df_teams,df_players=scrape.get_players(sport_id,year_input))
# stat_summary_table(df=df,
# ax=ax_season_table,
# player_input=player_input,
# split=input.split_id(),
# sport_id=sport_id)
# # break_plot(df=df_plot,ax=ax2)
# for x,y,z in zip([input.plot_id_1(),input.plot_id_2(),input.plot_id_3()],[ax_plot_1,ax_plot_2,ax_plot_3],[1,3,5]):
# if x == 'velocity_kdes':
# velocity_kdes(df,
# ax=y,
# gs=gs,
# gs_x=[3,4],
# gs_y=[z,z+2],
# fig=fig)
# if x == 'tj_stuff_roling':
# tj_stuff_roling(df=df,
# window=int(input.rolling_window()),
# ax=y)
# if x == 'tj_stuff_roling_game':
# tj_stuff_roling_game(df=df,
# window=int(input.rolling_window()),
# ax=y)
# if x == 'break_plot':
# break_plot(df = df,ax=y)
# if x == 'location_plot_lhb':
# location_plot(df = df,ax=y,hand='L')
# if x == 'location_plot_rhb':
# location_plot(df = df,ax=y,hand='R')
# summary_table(df=df,
# ax=ax_table)
# plot_footer(ax_footer)
# fig.subplots_adjust(left=0.01, right=0.99, top=0.99, bottom=0.01)
# fig.savefig('test.svg')
app = App(app_ui, server) |