Spaces:
Running
Running
File size: 25,438 Bytes
e0df468 eaab5cb aa03a67 eaab5cb aa03a67 9a59ac4 aa03a67 9a59ac4 aa03a67 eaab5cb aa03a67 eaab5cb aa03a67 eaab5cb aa03a67 eaab5cb aa03a67 eaab5cb aa03a67 eaab5cb aa03a67 eaab5cb aa03a67 eaab5cb 5f4d665 eaab5cb aa03a67 eaab5cb aa03a67 eaab5cb aa03a67 eaab5cb aa03a67 8750c69 aa03a67 eaab5cb aa03a67 eaab5cb aa03a67 eaab5cb aa03a67 eaab5cb d1f3cb7 aa03a67 eaab5cb aa03a67 d1f3cb7 8750c69 d1f3cb7 aa03a67 6ff8cda d1f3cb7 aa03a67 d1f3cb7 aa03a67 d1f3cb7 aa03a67 d1f3cb7 aa03a67 67efef9 d1f3cb7 aa03a67 d1f3cb7 8d537d3 aa03a67 8d537d3 aa03a67 d1f3cb7 aa03a67 8d537d3 aa03a67 8d537d3 aa03a67 8d537d3 aa03a67 b704539 aa03a67 7099c3e aa03a67 eaab5cb aa03a67 b704539 aa03a67 b704539 aa03a67 b704539 aa03a67 b704539 aa03a67 b704539 aa03a67 b704539 aa03a67 b704539 aa03a67 b704539 aa03a67 b704539 aa03a67 b704539 aa03a67 b704539 aa03a67 b704539 6ff8cda aa03a67 b704539 aa03a67 b704539 aa03a67 b704539 aa03a67 b704539 aa03a67 b704539 aa03a67 b704539 aa03a67 b704539 aa03a67 b704539 aa03a67 b704539 aa03a67 b704539 aa03a67 b704539 aa03a67 b704539 aa03a67 0f79932 b704539 aa03a67 b704539 aa03a67 b704539 aa03a67 b704539 aa03a67 b704539 aa03a67 b704539 aa03a67 b704539 aa03a67 6ff8cda aa03a67 eaab5cb 6ff8cda aa03a67 eaab5cb aa03a67 6ff8cda eaab5cb 523fd98 aa03a67 eaab5cb aa03a67 |
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 |
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
from scipy import stats
import pickle
import json
from datetime import timedelta
from urllib.request import urlopen
from datetime import date
from datetime import datetime
import pytz
import json
from matplotlib.ticker import MaxNLocator
import matplotlib.font_manager as font_manager
import numpy as np
# team_games_df = pd.read_csv('data/team_games_all.csv',index_col=[0])
# player_games_df = pd.read_csv('data/player_games_cards.csv',index_col=[0]).sort_values(by='date').reset_index(drop=True)
team_abv_nst = pd.read_csv('data/team_abv_nst.csv')
#player_games_df = player_games_df.loc[:, ~player_games_df.columns.str.contains('^Unnamed')]
#team_abv = pd.read_csv('team_abv.csv')
#team_games_df = team_games_df.merge(right=team_abv,left_on='team',right_on='team_name',how='left').drop(columns='team_name')
team_abv = pd.read_csv('data/team_abv.csv')
import pickle
from datetime import timedelta
# # Loop over the counter and format the API call
# r = requests.get('https://statsapi.web.nhl.com/api/v1/schedule?startDate=2022-10-01&endDate=2023-06-01')
# schedule = r.json()
schedule = json.loads(urlopen('https://statsapi.web.nhl.com/api/v1/schedule?startDate=2023-10-07&endDate=2024-04-19').read())
def flatten(t):
return [item for sublist in t for item in sublist]
game_id = flatten([[x['gamePk'] for x in schedule['dates'][y]['games']] for y in range(0,len(schedule['dates']))])
game_type = flatten([[x['gameType'] for x in schedule['dates'][y]['games']] for y in range(0,len(schedule['dates']))])
game_date = flatten([[(pd.to_datetime(x['gameDate']) - timedelta(hours=8)) for x in schedule['dates'][y]['games']] for y in range(0,len(schedule['dates']))])
game_final = flatten([[x['status']['detailedState'] for x in schedule['dates'][y]['games']] for y in range(0,len(schedule['dates']))])
game_home = flatten([[x['teams']['home']['team']['name'] for x in schedule['dates'][y]['games']] for y in range(0,len(schedule['dates']))])
game_away = flatten([[x['teams']['away']['team']['name'] for x in schedule['dates'][y]['games']] for y in range(0,len(schedule['dates']))])
schedule_df = pd.DataFrame(data={'game_id': game_id, 'game_type':game_type,'game_date' : game_date, 'game_home' : game_home, 'game_away' : game_away,'status' : game_final})
schedule_df = schedule_df[schedule_df.game_type == 'R'].reset_index(drop=True)
schedule_df = schedule_df[schedule_df.status != 'Postponed']
schedule_df = schedule_df.replace('Montréal Canadiens','Montreal Canadiens')
schedule_df_merge = schedule_df.merge(right=team_abv,left_on='game_home',right_on='team_name',how='left')
schedule_df_merge = schedule_df_merge.merge(right=team_abv,left_on='game_away',right_on='team_name',how='left')
schedule_df_merge = schedule_df_merge.drop(columns={'team_name_x','team_name_y'})
schedule_df_merge = schedule_df_merge.rename(columns={'team_abv_x' : 'team_abv_home','team_abv_y' : 'team_abv_away'})
#schedule_df_merge.game_date = pd.to_datetime(schedule_df_merge['game_date']).dt.tz_convert(tz='US/Eastern').dt.date
# schedule_df_merge = schedule_df_merge.set_index(pd.DatetimeIndex(schedule_df_merge.game_date).strftime('%Y-%m-%d'))
schedule_df_merge.index = pd.to_datetime(schedule_df_merge.game_date)
schedule_df_merge = schedule_df_merge.drop(columns='game_date')
#schedule_df_merge.index = schedule_df_merge.index.tz_convert('US/Pacific')
schedule_df_merge.index = schedule_df_merge.index.date
schedule_df_merge = schedule_df_merge.sort_index()
schedule_df_merge = schedule_df_merge[schedule_df_merge.index <= date(2024,5,1)]
schedule_df_merge_final = schedule_df_merge[schedule_df_merge['status']=='Final']
schedule_ccount_df = pd.DataFrame(data={'date':list(schedule_df_merge_final.index)*2,'team':list(schedule_df_merge_final.team_abv_away)+list(schedule_df_merge_final.team_abv_home)}).sort_values(by='date').reset_index(drop=True)
schedule_ccount_df['team_game'] = schedule_ccount_df.groupby('team').cumcount()+1
schedule_ccount_df.date = pd.to_datetime(schedule_ccount_df.date)
today = pd.to_datetime(datetime.now(pytz.timezone('US/Pacific')).strftime('%Y-%m-%d'))
team_schdule = schedule_df_merge[(schedule_df_merge['team_abv_home']=='EDM')|(schedule_df_merge['team_abv_away']=='EDM')]
team_schdule_live = team_schdule[team_schdule.index <= today]
team_schdule_live.head()
team_games_df = pd.read_csv('data/team_games_all.csv',index_col=[0])
player_games_df = pd.read_csv('data/player_games_cards.csv',index_col=[0]).sort_values(by='date').reset_index(drop=True)
team_abv_df = pd.read_csv('data/team_abv.csv')
player_games_df = player_games_df.loc[:, ~player_games_df.columns.str.contains('^Unnamed')]
team_games_df = team_games_df.merge(right=team_abv_df,left_on='team',right_on='team_name',how='left').drop(columns='team_name')
player_games_df = player_games_df.drop_duplicates(subset=['player_id','date'],keep='last').reset_index(drop=True)
player_games_df.date = pd.to_datetime(player_games_df.date)
team_games_df = team_games_df[team_games_df['date']=='Final']
schedule_df_merge_final = schedule_df_merge[schedule_df_merge['status']=='Final']
schedule_ccount_df = pd.DataFrame(data={'date':list(schedule_df_merge_final.index)*2,'team':list(schedule_df_merge_final.team_abv_away)+list(schedule_df_merge_final.team_abv_home)}).sort_values(by='date').reset_index(drop=True)
schedule_ccount_df['team_game'] = schedule_ccount_df.groupby('team').cumcount()+1
schedule_ccount_df.date = pd.to_datetime(schedule_ccount_df.date)
team_games_df['team_game'] = team_games_df.groupby('team').cumcount()+1
player_games_df = player_games_df.merge(right=schedule_ccount_df,left_on=['Team','date'],right_on=['team','date'],how='left')
player_games_df['player_game'] = player_games_df.groupby('player_id').cumcount()+1
date_range_list = pd.date_range(start=player_games_df.date.min()+timedelta(days=6),end=player_games_df.date.max())
team_abv_nst_dict = {'All':''} | team_abv_nst.set_index('team_abv')['team_name'].to_dict()
position_dict = {'All':'','F':'Forwards','D':'Defense'}
player_games_df = player_games_df.rename(columns={'Total Points_pp':'PP Points'})
stat_input_list = ['TOI', 'Goals', 'Total Assists',
'First Assists', 'Total Points', 'PP Points','Shots', 'Hits',
'Shots Blocked']
df_cum_stat_total = player_games_df.groupby(['player_id','Player','Position']).agg(
GP = ('GP','count'),
Total_Points = ('Total Points','sum')
).reset_index()
df_all_sort = df_cum_stat_total.copy()
stat_pick = 'Total_Points'
count=11
not_position = ''
team = ''
df_all_sort = df_all_sort[(df_all_sort['Position']!=not_position)]
df_all_sort[stat_pick+' per game'] = df_all_sort[stat_pick]/df_all_sort['GP']
df_all_sort[stat_pick+' Rank'] = df_all_sort[stat_pick].rank(ascending=False,method='min')
df_all_sort = df_all_sort[df_all_sort[stat_pick+' Rank']<=count]
df_all_sort[stat_pick+' per game Rank'] = df_all_sort[stat_pick+' per game'].rank(ascending=False,method='min')
# #df_all_sort.sort_values(by=[stat_pick,stat_pick+' per game','Total Points'],ascending = (False, False,False))
df_all_sort_list = df_all_sort[df_all_sort[stat_pick+' Rank']<max(df_all_sort[stat_pick+' Rank'])].sort_values(by=[stat_pick,stat_pick+' per game','Total_Points'],ascending = (False, False,False))
# # df_all_sort = df_all_sort.sort_values(by=[stat_pick,stat_pick+' per game','Total Points'],ascending = (False, False,False))[(df_all_sort['Position']!=not_position)&(df_all_sort['Team']!=team)].head(count)['Player']
temp_df = df_all_sort[df_all_sort[stat_pick+' Rank']==max(df_all_sort[stat_pick+' Rank'])]#[stat_pick+' per game Rank'].rank().sort_values(ascending=True).reset_index(drop=True)[count-len(df_all_sort_list)-1]
temp_df['temp'] = temp_df[stat_pick+' per game Rank'].rank()#.sort_values(ascending=True)#.reset_index(drop=True)
temp_df = temp_df.sort_values(by='temp',ascending=True)#.reset_index(drop=True)
temp = temp_df[temp_df['temp']<=(count-len(df_all_sort_list))]
players_list = list(pd.concat([df_all_sort_list,temp]).reset_index(drop=True)['player_id'])
rookie_df = pd.read_csv('data/player_rookies.csv',index_col=[0])
rookie_list = rookie_df.player_id.values
skater_dict = df_cum_stat_total.sort_values(by=['Total_Points','GP'],ascending=[False,True]).drop_duplicates(subset='player_id').set_index('player_id')#.sort_values(by='Player')
#skater_dict['skater_team'] = skater_dict.Player + ' - ' + skater_dict.Team
skater_dict = skater_dict['Player'].to_dict()
# players_list = list(df_all_sort['Player'])
print(players_list)
from shiny import ui, render, App
from shiny import App, reactive, ui
from shiny.ui import h2, tags
import matplotlib.image as mpimg
# app_ui = ui.page_fluid(
# # ui.output_plot("plot"),
# #ui.h2('MLB Batter Launch Angle vs Exit Velocity'),
# ui.layout_sidebar(
# ui.panel_sidebar(
# ui.input_select("id", "Select Batter",batter_dict),
# ui.input_select("plot_id", "Select Plot",{'scatter':'Scatter Plot','dist':'Distribution Plot'})))
# ,
# ui.panel_main(ui.output_plot("plot",height = "750px",width="1250px")),
# #ui.download_button('test','Download'),
# )
#import shinyswatch
app_ui = ui.page_fluid(
#shinyswatch.theme.cosmo(),
ui.layout_sidebar(
# Available themes:
# cerulean, cosmo, cyborg, darkly, flatly, journal, litera, lumen, lux,
# materia, minty, morph, pulse, quartz, sandstone, simplex, sketchy, slate,
# solar, spacelab, superhero, united, vapor, yeti, zephyr
ui.panel_sidebar(
ui.input_select("id", "Select Skater (max. 10 Skaters)",skater_dict,width=1,selected=list(players_list[0:10]),selectize=True,multiple=True),
ui.input_select("stat", "Stat Input",stat_input_list,width=1,size=1,selectize=False,selected='Total Points'),
ui.input_select("team_select", "Team",team_abv_nst_dict,width=1,size=1,selectize=False,selected='All'),
ui.input_select("position_select", "Position",position_dict,width=1,size=1,selectize=False,selected='All'),
ui.input_date("date", "Date input",value = datetime.today().date() - timedelta(days=1),min='2023-10-10', max=datetime.today().date() - timedelta(days=1)),
ui.input_switch("rookie_switch", "Rookies Only"),
ui.output_table("result"),
width=3),
ui.panel_main(
ui.navset_tab(
ui.nav("Chart Races",
ui.panel_main(
ui.output_plot("plot",height = "1200px",width="1200px")),
)
))))
# ui.row(
# ui.column(
# 3,
# ui.input_date("x", "Date input"),),
# ui.column(
# 1,
# ui.input_select("level_id", "Select Level",level_dict,width=1)),
# ui.column(
# 3,
# ui.input_select("stat_id", "Select Stat",plot_dict_small,width=1)),
# ui.column(
# 2,
# ui.input_numeric("n", "Rolling Window Size", value=50)),
# ),
# ui.output_table("result_batters")),
# ui.nav(
# "Pitchers",
# ui.row(
# ui.column(
# 3,
# ui.input_select("id_pitch", "Select Pitcher",pitcher_dict,width=1,selected=675911),
# ),
# ui.column(
# 1,
# ui.input_select("level_id_pitch", "Select Level",level_dict,width=1)),
# ui.column(
# 3,
# ui.input_select("stat_id_pitch", "Select Stat",plot_dict_small_pitch,width=1)),
# ui.column(
# 2,
# ui.input_numeric("n_pitch", "Rolling Window Size", value=50)),
# ),
# ui.output_table("result_pitchers")),
# )
# )
# )
#from urllib.request import Request, urlopen
# importing OpenCV(cv2) module
def server(input, output, session):
@reactive.Effect
def _():
team_select_list = [input.team_select()]
position_select_list = [input.position_select()]
if team_select_list[0] == 'All':
team_select_list = team_abv_nst.team_abv.unique()
if position_select_list[0] == 'All':
position_select_list = player_games_df.Position.unique()
elif position_select_list[0] == 'F':
position_select_list = player_games_df[player_games_df.Position != 'D'].Position.unique()
else:
position_select_list = ['D']
print(team_select_list)
if input.rookie_switch():
df_cum_stat_total = player_games_df[(player_games_df.date <= pd.to_datetime(input.date()))
&(player_games_df.player_id.isin(rookie_list))
&(player_games_df.Team.isin(team_select_list))
&(player_games_df.Position.isin(position_select_list))].groupby(['player_id','Player','Position']).agg(
GP = ('GP','count'),
Total_Points = (f'{input.stat()}','sum')
).reset_index()
else:
df_cum_stat_total = player_games_df[(player_games_df.date <= pd.to_datetime(input.date()))
&(player_games_df.Team.isin(team_select_list))
&(player_games_df.Position.isin(position_select_list))].groupby(['player_id','Player','Position']).agg(
GP = ('GP','count'),
Total_Points = (f'{input.stat()}','sum')
).reset_index()
df_all_sort = df_cum_stat_total.copy()
stat_pick = 'Total_Points'
count=6
not_position = ''
team = ''
df_all_sort = df_all_sort[(df_all_sort['Position']!=not_position)]
df_all_sort[stat_pick+' per game'] = df_all_sort[stat_pick]/df_all_sort['GP']
df_all_sort[stat_pick+' Rank'] = df_all_sort[stat_pick].rank(ascending=False,method='min')
df_all_sort = df_all_sort[df_all_sort[stat_pick+' Rank']<=count]
df_all_sort[stat_pick+' per game Rank'] = df_all_sort[stat_pick+' per game'].rank(ascending=False,method='min')
# #df_all_sort.sort_values(by=[stat_pick,stat_pick+' per game','Total Points'],ascending = (False, False,False))
df_all_sort_list = df_all_sort[df_all_sort[stat_pick+' Rank']<max(df_all_sort[stat_pick+' Rank'])].sort_values(by=[stat_pick,stat_pick+' per game','Total_Points'],ascending = (False, False,False))
# # df_all_sort = df_all_sort.sort_values(by=[stat_pick,stat_pick+' per game','Total Points'],ascending = (False, False,False))[(df_all_sort['Position']!=not_position)&(df_all_sort['Team']!=team)].head(count)['Player']
temp_df = df_all_sort[df_all_sort[stat_pick+' Rank']==max(df_all_sort[stat_pick+' Rank'])]#[stat_pick+' per game Rank'].rank().sort_values(ascending=True).reset_index(drop=True)[count-len(df_all_sort_list)-1]
temp_df['temp'] = temp_df[stat_pick+' per game Rank'].rank()#.sort_values(ascending=True)#.reset_index(drop=True)
temp_df = temp_df.sort_values(by='temp',ascending=True)#.reset_index(drop=True)
temp = temp_df[temp_df['temp']<=(count-len(df_all_sort_list))]
players_list_new = list(pd.concat([df_all_sort_list,temp]).reset_index(drop=True)['player_id'])
skater_dict = df_cum_stat_total.sort_values(by=['Total_Points','GP'],ascending=[False,True]).drop_duplicates(subset='player_id').set_index('player_id')#.sort_values(by='Player')
#skater_dict['skater_team'] = skater_dict.Player + ' - ' + skater_dict.Team
skater_dict = skater_dict['Player'].to_dict()
# players_list = list(df_all_sort['Player'])
ui.update_select(
"id",
label="Select Skater (max. 10 Skaters)",
choices=skater_dict,
selected=list(players_list_new[0:10]))
@output
@render.table
def result():
if input.rookie_switch():
return player_games_df[(player_games_df.date <= pd.to_datetime(input.date()))&(player_games_df.player_id.isin(rookie_list))].groupby(['player_id','Player','Position']).agg(
GP = ('GP','count'),
Stat = (f'{input.stat()}','sum')
).reset_index().sort_values(by=['Stat','GP'],ascending=[False,True]).reset_index(drop=True)
else:
return player_games_df[player_games_df.date <= pd.to_datetime(input.date())].groupby(['player_id','Player','Position']).agg(
GP = ('GP','count'),
Stat = (f'{input.stat()}','sum')
).reset_index().sort_values(by=['Stat','GP'],ascending=[False,True]).reset_index(drop=True)
@output
@render.plot(alt="A histogram")
def plot():
team_select_list = [input.team_select()]
position_select_list = [input.position_select()]
if team_select_list[0] == 'All':
team_select_title = 'NHL '
else:
team_select_title = f'{team_abv_nst_dict[team_select_list[0]]} '
if position_select_list[0] == 'All':
position_select_title = ''
elif position_select_list[0] == 'F':
position_select_title = 'Forwards '
else:
position_select_title = 'Defense '
rookie = ''
if input.rookie_switch():
rookie = 'Rookie '
i = 0
#rookie = ''
current_season = '2023'
start_season = '2024'
# player_lookup_list = ['Connor McDavid','David Pastrnak','Nathan MacKinnon']
type(input.id())
print(input.id())
player_lookup_list = list(input.id())[0:10]
stat = input.stat()
sns.set_theme(style="whitegrid", palette="pastel")
#print(type([input.date()))
date_range_list = [pd.to_datetime(input.date())]
for k in range(len(date_range_list)):
print(date_range_list[k])
stat = input.stat()
team_schedule_url_merge = []
max_games_player = []
max_games_team = []
max_stat = []
per_game = False
for i in range(0,len(player_lookup_list)):
team_schedule_url_merge.append(player_games_df[(player_games_df.player_id == int(player_lookup_list[i]))&(date_range_list[k] >= player_games_df.date)].reset_index(drop=True))
#print('touble',i, player_lookup_list[i],len(player_games_df[(player_games_df.player_id == player_lookup_list[i])]))
team_schedule_url_merge[i].index = team_schedule_url_merge[i].team_game
team_schedule_url_merge[i] = team_schedule_url_merge[i].reindex(np.arange(team_schedule_url_merge[i].team_game.min(), team_schedule_url_merge[i].team_game.max() + 1)).reset_index(drop=True)
#team_schedule_url_merge[0]['team_game'] = team_schedule_url_merge[0]['index']
#team_schedule_url_merge[0]['player_game'] =
#schedule_ccount_df[schedule_ccount_df['team'].isin(team_schedule_url_merge[0].Team.unique())].merge(right=team_schedule_url_merge[0],left_on=['date','team'],right_on=['date','Team'],how='left')
team_schedule_url_merge[i]['stat'] = team_schedule_url_merge[i][stat].cumsum()
#team_schedule_url_merge[i]['stat'] = team_schedule_url_merge[i][stat_pick]
team_schedule_url_merge[i] = team_schedule_url_merge[i].append(team_schedule_url_merge[i]).sort_index()
team_schedule_url_merge[i] = team_schedule_url_merge[i].append(team_schedule_url_merge[i].iloc[0]).sort_index().reset_index(drop=True)
team_schedule_url_merge[i]['team_game'][0] = 0
team_schedule_url_merge[i]['player_game'][0] = 0
team_schedule_url_merge[i]['stat'][0] = 0
for j in range(1,len(team_schedule_url_merge[i]),2):
team_schedule_url_merge[i]['player_game'][j] = team_schedule_url_merge[i]['player_game'][j]-1
team_schedule_url_merge[i]['team_game'][j] = team_schedule_url_merge[i]['team_game'][j]-1
team_schedule_url_merge[i]['stat'][j] = team_schedule_url_merge[i]['stat'][j] - team_schedule_url_merge[i][stat][j]
if len(team_schedule_url_merge[i]) >3:
if pd.isna(team_schedule_url_merge[i].iloc[3]['player_game']) and pd.isna(team_schedule_url_merge[i].iloc[1]['player_game']) == True:
team_schedule_url_merge[i]['player_game'][2] = np.nan
team_schedule_url_merge[i]['stat'][2] = np.nan
if len(team_schedule_url_merge[i]) >3:
if pd.isna(team_schedule_url_merge[i].iloc[len(team_schedule_url_merge[i])-1]['player_game']) == True:
team_schedule_url_merge[i]['stat'][len(team_schedule_url_merge[i])-1] = np.nanmax(team_schedule_url_merge[i]['stat'])
if not (team_schedule_url_merge[i]['team_game'].values[1] == team_schedule_url_merge[i]['player_game'].values[0]):
team_schedule_url_merge[i].loc[0,'team_game'] = np.nan
max_games_player.append(np.around(np.nanmax(team_schedule_url_merge[i]['player_game'])))
max_games_team.append(np.around(np.nanmax(team_schedule_url_merge[i]['team_game'])))
max_stat.append((np.around(np.nanmax(team_schedule_url_merge[i]['stat']))))
fig, ax = plt.subplots(figsize=(15,15))
cgfont = {'fontname':'Century Gothic'}
font = font_manager.FontProperties(family='Century Gothic',
style='normal', size=14)
ax.axhline(0,color='black',linestyle ="--",linewidth=2,alpha=1.0,label='Missed Games')
ax.axhline(0,color='black',linestyle ="-",linewidth=2,alpha=1.0)
if 'Total' in stat:
stat = stat.replace('Total ',"")
colour_scheme = ['#648FFF','#785EF0','#DC267F','#FE6100','#FFB000','#FAEF3B','#861318','#2ED3BC','#341BBF','#B37E2C']
for i in range(len(team_schedule_url_merge)):
sns.lineplot(team_schedule_url_merge[i].reset_index()['team_game'],team_schedule_url_merge[i].reset_index()['stat'],linewidth=3-i*.2,color=colour_scheme[i])
plt.plot(team_schedule_url_merge[i]['team_game'],team_schedule_url_merge[i]['stat'],color=ax.lines[i*2+2].get_color(),label=str(i+1)+'. '+team_schedule_url_merge[i]['Player'][0]+', '+str(int(max_stat[i]))+' '+stat+' in '+str(int(max(team_schedule_url_merge[i]['player_game'])))+' Games',linewidth=6)
ax.lines[i*2+2].set_linestyle("--")
fig.set_facecolor('#ffffff')
ax.set(xlim=(0,max([team_schedule_url_merge[x].team_game.max() for x in range(len(team_schedule_url_merge))])))
ax.set(ylim=(0,max([team_schedule_url_merge[x].stat.max() for x in range(len(team_schedule_url_merge))])))
ax.legend_.remove()
if per_game == False:
fig.suptitle(f'{rookie}{team_select_title}{position_select_title}{stat} Race',y=.98,fontsize=32,color='black',**cgfont)
ax.set_ylabel(stat,fontsize=20,color='black',**cgfont)
# else:
# fig.suptitle(stat+' Per Game, All Situations',y=.99,fontsize=48,color='black',**cgfont)
# ax.set_ylabel(stat+"/GP",fontsize=20,color='black',**cgfont)
ax.set_title(str(current_season)[0:4]+'-'+str(start_season)[-4:]+' Season',y=1.01,fontsize=18,color='black',**cgfont,x=0,ha='left')
ax.set_xlabel('Team Game',fontsize=20,color='black',**cgfont)
ax.tick_params(axis="x", labelsize=24,colors='black')
ax.set_facecolor('#ffffff')
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
ax.tick_params(axis="y", labelsize=24,colors='black')
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
fig.text(x=0.025,y=0.01,s="Created By: @TJStats",color='black', fontsize=20, horizontalalignment='left',**cgfont)
fig.text(x=0.975,y=0.01,s="Data: Natural Stat Trick",color='black', fontsize=20, horizontalalignment='right',**cgfont)
fig.text(x=.975,y=0.92,s='Date: '+input.date().strftime('%B %d, %Y'),color='black', fontsize=18, horizontalalignment='right',**cgfont)
ax.legend(prop=font,bbox_to_anchor=(0.01, 0.99),loc='upper left',framealpha=1,frameon=True)
plt.tight_layout()
#fig.savefig('gif_race/'+stat+rookie+str(date_range_list[k].date())+'.png', facecolor=fig.get_facecolor(), edgecolor='none',bbox_inches='tight',dpi=100)
#plt.close()
#fig.legend(prop=font,loc='best',framealpha=1,frameon=True)
app = App(app_ui, server) |