Spaces:
Running
Running
File size: 63,737 Bytes
9a59ac4 eaab5cb e0df468 eaab5cb 9a59ac4 7099c3e c3ad087 eaab5cb 9a59ac4 eaab5cb 9a59ac4 eaab5cb b704539 1faf464 9a59ac4 eaab5cb 1faf464 9a59ac4 1faf464 9a59ac4 1faf464 b704539 9a59ac4 1faf464 9a59ac4 eaab5cb b704539 eaab5cb a6b368c eaab5cb b704539 8830a95 b704539 9a59ac4 f7e116f 381bd35 139dc35 381bd35 b704539 9a59ac4 6c730a1 7e5d21f 45ba206 6c730a1 88da8cb 9a59ac4 815e584 b704539 9a59ac4 b704539 9a59ac4 b704539 9a59ac4 b704539 3f2f598 45ba206 f86e382 6c730a1 b704539 eaab5cb 45ba206 9a59ac4 3f2f598 9a59ac4 3f2f598 9a59ac4 eaab5cb 9a59ac4 5f4d665 b704539 db59c68 b704539 9a59ac4 eaab5cb 9a59ac4 eaab5cb 9a59ac4 eaab5cb b704539 eaab5cb 5f4d665 b704539 eaab5cb b704539 eaab5cb b704539 7099c3e b704539 6c730a1 b704539 381bd35 b704539 eaab5cb b704539 eaab5cb 9a59ac4 eaab5cb b704539 139dc35 863a048 b704539 863a048 b704539 262276f b704539 863a048 b704539 863a048 b704539 d1f3cb7 863a048 b704539 863a048 b704539 863a048 eaab5cb b704539 d1f3cb7 b704539 d1f3cb7 b704539 d1f3cb7 b704539 d1f3cb7 b704539 d1f3cb7 b704539 d1f3cb7 cd89137 cdfcca2 c19fadc cdfcca2 1117af8 b704539 d1f3cb7 67efef9 8d537d3 d1f3cb7 8d537d3 2a766df d1f3cb7 8d537d3 d1f3cb7 8d537d3 2a766df 8d537d3 b704539 eaab5cb b704539 521fb64 7099c3e 3ea742d b704539 7ba0a28 3ea742d 7ba0a28 3ea742d 58d1cbc eaab5cb 3ea742d 827bbf4 f154443 b704539 6de20f1 b704539 381bd35 b704539 f154443 b704539 eaab5cb ae30f51 eaab5cb b704539 eaab5cb 4fc67c7 eaab5cb b704539 3966ce9 b704539 f8e8024 b704539 f8e8024 b704539 381bd35 b704539 6fd14b3 b704539 4aaf3a4 b704539 4aaf3a4 b704539 381bd35 b704539 7ea4826 b704539 eaab5cb 9a59ac4 eaab5cb 073a4a7 d1f3cb7 |
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 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 |
print('Running')
import time
import requests
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
import matplotlib.lines as mlines
import matplotlib.transforms as mtransforms
import numpy as np
import time
from urllib.error import HTTPError
#import plotly.express as px
#!pip install chart_studio
#import chart_studio.tools as tls
from bs4 import BeautifulSoup
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.font_manager as font_manager
from datetime import datetime
import pytz
from matplotlib.ticker import MaxNLocator
from matplotlib.patches import Ellipse
import matplotlib.transforms as transforms
from matplotlib.gridspec import GridSpec
datetime.now(pytz.timezone('US/Pacific')).strftime('%B %d, %Y')
# Configure Notebook
#%matplotlib inline
plt.style.use('fivethirtyeight')
sns.set_context("notebook")
import warnings
warnings.filterwarnings('ignore')
# import dataframe_image as dfi
# from google.colab import drive
def percentile(n):
def percentile_(x):
return np.percentile(x, n)
percentile_.__name__ = 'percentile_%s' % n
return percentile_
# import os
# import praw
# import matplotlib.pyplot as plt
# import matplotlib.colors
# import matplotlib.colors as mcolors
# cmap_sum = matplotlib.colors.LinearSegmentedColormap.from_list("", ["#4285f4","#FFFFFF","#F0E442"])
#import pybaseball
import math
# import matplotlib.ticker as mtick
# import matplotlib.ticker as ticker
# colour_palette = ['#FFB000','#648FFF','#785EF0',
# '#DC267F','#FE6100','#3D1EB2','#894D80','#16AA02','#B5592B','#A3C1ED']
# import matplotlib.colors as mcolors
# from matplotlib.ticker import FuncFormatter
# from matplotlib.font_manager import FontProperties
import matplotlib.ticker as mtick
import numpy as np
# import matplotlib.pyplot as plt
import matplotlib.colors
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize
from matplotlib import cm
from datetime import date
def show_values(axs, orient="v", space=-1,stat = [],rank_n=[]):
def _single(ax):
if orient == "v":
i = 0
for p in ax.patches:
_x = p.get_x() + p.get_width() / 2
_y = p.get_y() + p.get_height() + (p.get_height()*0.01)
value = '{:.0f}'.format(p.get_height())
if isinstance(stat[i], float):
value_stat = '{:.2f}'.format(stat[i])
else:
value_stat = stat[i]
rank = rank_n[i]
ax.text(_x, -3.8, value_stat, ha="center",fontstyle='italic')
ax.text(_x, -4.2, rank, ha="center",fontstyle='italic')
i = i+1
elif orient == "h":
for p in ax.patches:
_x = p.get_x() + p.get_width() + float(space)
_y = p.get_y() + p.get_height() - (p.get_height()*0.5)
value = '{:.0f}'.format(p.get_width())
ax.text(_x, _y, value, ha="left")
if isinstance(axs, np.ndarray):
for idx, ax in np.ndenumerate(axs):
_single(ax)
else:
_single(axs)
data_r = requests.get("https://pub-api-ro.fantasysports.yahoo.com/fantasy/v2/league/427.l.public;out=settings/players;position=ALL;start=0;count=3000;sort=rank_season;search=;out=percent_owned;out=auction_values,ranks;ranks=season;ranks_by_position=season;out=expert_ranks;expert_ranks.rank_type=projected_season_remaining/draft_analysis;cut_types=diamond;slices=last7days?format=json_f").json()
total_list = []
for x in data_r['fantasy_content']['league']['players']:
single_list = []
single_list.append(int(x['player']['player_id']))
single_list.append(int(x['player']['player_ranks'][0]['player_rank']['rank_value']))
single_list.append(x['player']['name']['full'])
single_list.append(x['player']['name']['first'])
single_list.append(x['player']['name']['last'])
single_list.append(x['player']['draft_analysis']['average_pick'])
single_list.append(x['player']['average_auction_cost'])
single_list.append(x['player']['display_position'])
single_list.append(x['player']['editorial_team_abbr'])
if 'value' in x['player']['percent_owned']:
single_list.append(x['player']['percent_owned']['value']/100)
else:
single_list.append(0)
total_list.append(single_list)
df_2023 = pd.DataFrame(data=total_list,columns=['player_id','rank_value','full','first','last','average_pick', 'average_cost','display_position','editorial_team_abbr','percent_owned'])
df_2023['pos_new'] = ['D' if "D" in x else 'F' for x in df_2023['display_position']]
player_games = pd.read_csv('Drive/player_games_cards.csv',index_col=[0]).sort_values(by='date').drop_duplicates(subset=['player_id','date'])
summary_2023 = pd.read_csv('Drive/summary_2025.csv',index_col=[0])#.drop_duplicates(subset=['player_id'])
summary_2022 = pd.read_csv('Drive/summary_2024.csv',index_col=[0])
team_games = pd.read_csv('Drive/team_games.csv',index_col=[0])
nhl_logos = pd.read_csv("NHL Logos - NHL Logos.csv")
team_games = team_games.merge(right=nhl_logos[['Team Name','Team']],left_on=['team'],right_on=['Team Name'],how='left')
player_games.player_id = player_games.player_id.astype(int)
summary_2023.player_id = summary_2023.player_id.astype(int)
summary_2022.player_id = summary_2022.player_id.astype(int)
#summary_2022 = summary_2022.drop_duplicates(subset='player_id')
yahoo_to_nhl_df = pd.read_csv('yahoo_to_nhl.csv', encoding='unicode_escape')
yahoo_to_nhl_df = yahoo_to_nhl_df.merge(df_2023,left_on='player_id_yahoo',right_on='player_id')
summary_2023 = summary_2023.merge(yahoo_to_nhl_df,left_on='player_id',right_on='nhl_id',suffixes=['','_yahoo'],how='left')
summary_2023 = summary_2023.merge(right=player_games.drop_duplicates(subset=['player_id'],keep='last')[['player_id','Position','Team']],left_on=['player_id'],right_on=['player_id'],how='left')
summary_2023.loc[summary_2023.display_position.isna(),'display_position'] = summary_2023.loc[summary_2023.display_position.isna(),'Position']
summary_2023.display_position = summary_2023.display_position.replace({'L':'LW','R':'RW'})
summary_2023.percent_owned = summary_2023.percent_owned.fillna(0)
player_games['game'] = player_games.groupby(['player_id']).cumcount() + 1
summary_2023 = summary_2023.drop_duplicates(subset='player_id')
skater_dict = summary_2023.set_index('player_id').sort_values(by='Player')
skater_dict['skater_team'] = skater_dict.Player + ' - ' + skater_dict.Team
skater_dict = skater_dict['skater_team'].to_dict()
from shiny import ui, render, App
import matplotlib.image as mpimg
app_ui = ui.page_fluid(
#ui.panel_title("Simulate a normal distribution"),
ui.layout_sidebar(
ui.panel_sidebar(
#ui.input_date_range("date_range_id", "Date range input",start = statcast_df.game_date.min(), end = statcast_df.game_date.max()),
ui.input_select("id", "Select Skater",skater_dict,width=1,selected=8480069,selectize=True),
#ui.input_select("id", "Select Skater",skater_dict,width=1),
ui.input_numeric("last_game_id", "Select Last 'n' Games",value=1,width=1),
#ui.input_select("ignore_id", "Remove Columns",['Position','Roster%'],multiple=True,selectize=True),
width=2),
ui.panel_main(
ui.output_plot("plot",height = "1350px",width="2400px")
)
),
)
from urllib.request import Request, urlopen
from shiny import App, reactive, ui
from shiny.ui import h2, tags
# importing OpenCV(cv2) module
#print(app_ui)
def server(input, output, session):
@output
@render.plot(alt="A histogram")
def plot():
# from matplotlib import rc, font_manager
# rc('text', usetex=True)
# rc('font',**{'family':'sans-serif','sans-serif':['Century Gothic']})
#fig.set_facecolor('white')
sns.set_theme(style="whitegrid", palette="pastel")
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", ["#4285F4","white","#FBBC04"])
try:
if sum(summary_2023.player_id.isin([int(input.id())]))<1:
fig, ax = plt.subplots(figsize=(10,16))
fig.set_facecolor('white')
fig.text(s=f'Select Player From List',x=0.5,y=0.5,fontsize=28,ha='center')
return
except ValueError:
fig, ax = plt.subplots(figsize=(10,16))
fig.set_facecolor('white')
fig.text(s=f'Select Player From List',x=0.5,y=0.5,fontsize=28,ha='center')
return
player_id = int(input.id())
last_games = input.last_game_id()
player_games_one = player_games[player_games['player_id']==player_id].sort_values(by='game',ascending=False)
print(player_games_one)
summary_2023_one = summary_2023[summary_2023['player_id']==player_id]
summary_2022_one = summary_2022[summary_2022['player_id']==player_id]
last_games = min(last_games,max(summary_2023_one.GP.max()-1,1))
name = player_games_one.Player.values[0]
df_last_games = pd.DataFrame(data={'Games':[last_games]})
df_last_games['TOI'] = player_games_one['TOI'][:last_games].sum()
df_last_games['TOI/G'] = player_games_one['TOI'][:last_games].sum()/df_last_games.Games
df_last_games['PP TOI/G'] = player_games_one['TOI_pp'][:last_games].sum()/df_last_games.Games
df_last_games['Points/60'] = player_games_one['Total Points'][:last_games].sum()/df_last_games.TOI*60
df_last_games['Shots/60'] = player_games_one['Shots'][:last_games].sum()/df_last_games.TOI*60
df_last_games['Hits/60'] = player_games_one['Hits'][:last_games].sum()/df_last_games.TOI*60
df_last_games['Blocks/60'] = player_games_one['Shots Blocked'][:last_games].sum()/df_last_games.TOI*60
df_last_games['Goals/60'] = player_games_one['Goals'][:last_games].sum()/df_last_games.TOI*60
df_last_games['ixG/60'] = player_games_one['ixG'][:last_games].sum()/df_last_games.TOI*60
df_last_games['G-ixG/60'] = df_last_games['Goals/60'] - df_last_games['ixG/60']
df_last_games['iCF/60'] = player_games_one['iCF'][:last_games].sum()/df_last_games.TOI*60
df_last_games['iSCF/60'] = player_games_one['iSCF'][:last_games].sum()/df_last_games.TOI*60
df_last_games['iHDCF/60'] = player_games_one['iHDCF'][:last_games].sum()/df_last_games.TOI*60
df_last_games['GF/60'] = player_games_one['GF'][:last_games].sum()/df_last_games.TOI*60
df_last_games['xGF/60'] = player_games_one['xGF'][:last_games].sum()/df_last_games.TOI*60
df_last_games['IPP'] = player_games_one['Total Points'][:last_games].sum()/player_games_one['GF'][:last_games].sum()
df_last_games['S%'] = player_games_one['Goals'][:last_games].sum()/player_games_one['Shots'][:last_games].sum()
df_last_games['xS%'] = player_games_one['ixG'][:last_games].sum()/player_games_one['Shots'][:last_games].sum()
df_last_games['1st Assist%'] = player_games_one['First Assists'][:last_games].sum()/player_games_one['Total Assists'][:last_games].sum()
df_last_games['Off. Zone Start%'] = player_games_one['Off.\xa0Zone Starts'][:last_games].sum()/(player_games_one['Off.\xa0Zone Starts'][:last_games].sum()+player_games_one['Def.\xa0Zone Starts'][:last_games].sum())
df_last_games['oiSH%'] = player_games_one['GF'][:last_games].sum()/player_games_one['SF'][:last_games].sum()
df_season = pd.DataFrame(data={'Games':[len(player_games_one)]})
df_season['TOI'] = player_games_one['TOI'][:len(player_games_one)].sum()
df_season['TOI/G'] = player_games_one['TOI'][:len(player_games_one)].sum()/df_season.Games
df_season['PP TOI/G'] = player_games_one['TOI_pp'][:len(player_games_one)].sum()/df_season.Games
df_season['Points/60'] = player_games_one['Total Points'][:len(player_games_one)].sum()/df_season.TOI*60
df_season['Shots/60'] = player_games_one['Shots'][:len(player_games_one)].sum()/df_season.TOI*60
df_season['Hits/60'] = player_games_one['Hits'][:len(player_games_one)].sum()/df_season.TOI*60
df_season['Blocks/60'] = player_games_one['Shots Blocked'][:len(player_games_one)].sum()/df_season.TOI*60
df_season['Goals/60'] = player_games_one['Goals'][:len(player_games_one)].sum()/df_season.TOI*60
df_season['ixG/60'] = player_games_one['ixG'][:len(player_games_one)].sum()/df_season.TOI*60
df_season['G-ixG/60'] = df_season['Goals/60'] - df_season['ixG/60']
df_season['iCF/60'] = player_games_one['iCF'][:len(player_games_one)].sum()/df_season.TOI*60
df_season['iSCF/60'] = player_games_one['iSCF'][:len(player_games_one)].sum()/df_season.TOI*60
df_season['iHDCF/60'] = player_games_one['iHDCF'][:len(player_games_one)].sum()/df_season.TOI*60
df_season['GF/60'] = player_games_one['GF'][:len(player_games_one)].sum()/df_season.TOI*60
df_season['xGF/60'] = player_games_one['xGF'][:len(player_games_one)].sum()/df_season.TOI*60
df_season['IPP'] = player_games_one['Total Points'][:len(player_games_one)].sum()/player_games_one['GF'][:len(player_games_one)].sum()
df_season['S%'] = player_games_one['Goals'][:len(player_games_one)].sum()/player_games_one['Shots'][:len(player_games_one)].sum()
df_season['xS%'] = player_games_one['ixG'][:len(player_games_one)].sum()/player_games_one['Shots'][:len(player_games_one)].sum()
df_season['1st Assist%'] = player_games_one['First Assists'][:len(player_games_one)].sum()/player_games_one['Total Assists'][:len(player_games_one)].sum()
df_season['Off. Zone Start%'] = player_games_one['Off.\xa0Zone Starts'][:len(player_games_one)].sum()/(player_games_one['Off.\xa0Zone Starts'][:len(player_games_one)].sum()+player_games_one['Def.\xa0Zone Starts'][:len(player_games_one)].sum())
df_season['oiSH%'] = player_games_one['GF'][:len(player_games_one)].sum()/player_games_one['SF'][:len(player_games_one)].sum()
df_last_games.rename(index={0:'Last '+str(df_last_games.Games[0])+' GP'},inplace=True)
df_season.rename(index={0:'2023-24 ('+str(df_season.Games[0])+'GP)'},inplace=True)
# cols_to_use = summary_all.columns.difference(summary_all_on_ice.columns)
# df_career_total = summary_all.merge(summary_all_on_ice, left_index=True, right_index=True,
# how='outer', suffixes=('', '_y'))
# df_career_total.drop(df_career_total.filter(regex='_y$').columns, axis=1, inplace=True)
# df_career_total = df_career_total.merge(summary_pp, left_index=True, right_index=True,
# how='outer', suffixes=('', '_y'))
# df_career_total.drop(df_career_total.filter(regex='_y$').columns, axis=1, inplace=True)
# df_career_total = df_career_total.merge(summary_pp_on_ice, left_index=True, right_index=True,
# how='outer', suffixes=('', '_y'))
# df_career_total.drop(df_career_total.filter(regex='_y$').columns, axis=1, inplace=True)
df_career_total = summary_2022_one.sort_index(ascending=False)
df_career_total.columns = [c.replace(u"\xa0", u" ") for c in list(df_career_total.columns)]
df_career = pd.DataFrame(data={'Games':[df_career_total.GP.sum()]})
df_career['TOI'] = df_career_total['TOI'].sum()
df_career['TOI/G'] = df_career_total['TOI'].sum()/df_career.Games
df_career['PP TOI/G'] = df_career_total['TOI_pp'].sum()/df_career.Games
df_career['Points/60'] = df_career_total['Total_Points'].sum()/df_career_total.TOI.sum()*60
df_career['Shots/60'] = df_career_total['Shots'].sum()/df_career_total.TOI.sum()*60
df_career['Hits/60'] = df_career_total['Hits'].sum()/df_career_total.TOI.sum()*60
df_career['Blocks/60'] = df_career_total['Shots_Blocked'].sum()/df_career_total.TOI.sum()*60
df_career['Goals/60'] = df_career_total['Goals'].sum()/df_career_total.TOI.sum()*60
df_career['ixG/60'] = df_career_total['ixG'].sum()/df_career_total.TOI.sum()*60
df_career['G-ixG/60'] = df_career['Goals/60'] - df_career['ixG/60']
df_career['iCF/60'] = df_career_total['iCF'].sum()/df_career_total.TOI.sum()*60
df_career['iSCF/60'] = df_career_total['iSCF'].sum()/df_career_total.TOI.sum()*60
df_career['iHDCF/60'] = df_career_total['iHDCF'].sum()/df_career_total.TOI.sum()*60
df_career['GF/60'] = df_career_total['GF'].sum()/df_career_total.TOI.sum()*60
df_career['xGF/60'] = df_career_total['xGF'].sum()/df_career_total.TOI.sum()*60
df_career['IPP'] = df_career_total['Total_Points'].sum()/df_career_total['GF'].sum()
df_career['S%'] = df_career_total['Goals'].sum()/df_career_total['Shots'].sum()
df_career['xS%'] = df_career_total['ixG'].sum()/df_career_total['Shots'].sum()
df_career['1st Assist%'] = df_career_total['First_Assists'].sum()/df_career_total['Assists'].sum()
df_career['Off. Zone Start%'] = df_career_total['OZ Start%'].sum()
df_career['oiSH%'] = df_career_total['GF'].sum()/df_career_total['SF'].sum()
df_career.rename(index={0:'2023-24 ('+str(df_career.Games[0])+'GP)'},inplace=True)
df_combined = df_last_games.append([df_season,df_career])
df_combined_t = round(df_combined,3).transpose()
df_combined.style.format(formatter={"IPP": "{:.1%}","S%": "{:.1%}","1st Assist%": "{:.1%}","Off. Zone Start%": "{:.1%}","oiSH%": "{:.1%}"}).set_precision(2)
rows = [idx for idx in df_combined_t.index if '/' not in idx]
df_combined_t = df_combined_t.astype(float).fillna(0)
# df_combined_t_style = df_combined_t.style.set_table_styles([{
# 'selector': 'caption',
# 'props': [
# ('color', ''),
# ('fontname', 'Century Gothic'),
# ('font-size', '12px'),
# ('font-style', 'italic'),
# ('font-weight', ''),
# ('text-align', 'centre'),
# ]
# },{'selector' :'th', 'props':[('text-align', 'center'),('Height','8px')]},{'selector' :'td', 'props':[('text-align', 'center'),('font-size', '10px')]}],overwrite=False).set_properties(
# **{'background-color':'White','index':'White','min-width':'60px'},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', '18px')]}],overwrite=False).set_properties(
# **{'Height': '8px'},**{'text-align': 'center'},overwrite=False).apply(
# lambda x: ["background: #FEEFC1" if (i < 1 and v > x.iloc[1]*1.05) else "" for i,v in enumerate(x)], axis = 1,subset = (list(df_combined_t.index[2:]), list(df_combined_t.columns))).apply(
# lambda x: ["background: #FEEFC1" if (i == 1 and v > x.iloc[2]*1.05) else "" for i,v in enumerate(x)], axis = 1,subset = (list(df_combined_t.index[2:]), list(df_combined_t.columns))).apply(
# lambda x: ["background: #D0E1FD" if (i < 1 and v < x.iloc[1]*0.95) else "" for i,v in enumerate(x)], axis = 1,subset = (list(df_combined_t.index[2:]), list(df_combined_t.columns))).apply(
# lambda x: ["background: #D0E1FD" if (i == 1 and v < x.iloc[2]*0.95) else "" for i,v in enumerate(x)], axis = 1,subset = (list(df_combined_t.index[2:]), list(df_combined_t.columns))).apply(
# lambda x: ["background: #FDDE82" if (i < 1 and v > x.iloc[1]*1.1) else "" for i,v in enumerate(x)], axis = 1,subset = (list(df_combined_t.index[2:]), list(df_combined_t.columns))).apply(
# lambda x: ["background: #FDDE82" if (i == 1 and v > x.iloc[2]*1.1) else "" for i,v in enumerate(x)], axis = 1,subset = (list(df_combined_t.index[2:]), list(df_combined_t.columns))).apply(
# lambda x: ["background: #A1C2FA" if (i < 1 and v < x.iloc[1]*0.9) else "" for i,v in enumerate(x)], axis = 1,subset = (list(df_combined_t.index[2:]), list(df_combined_t.columns))).apply(
# lambda x: ["background: #A1C2FA" if (i == 1 and v < x.iloc[2]*0.9) else "" for i,v in enumerate(x)], axis = 1,subset = (list(df_combined_t.index[2:]), list(df_combined_t.columns))).apply(
# lambda x: ["background: #FCCD43" if (i < 1 and v > x.iloc[1]*1.15) else "" for i,v in enumerate(x)], axis = 1,subset = (list(df_combined_t.index[2:]), list(df_combined_t.columns))).apply(
# lambda x: ["background: #FCCD43" if (i == 1 and v > x.iloc[2]*1.15) else "" for i,v in enumerate(x)], axis = 1,subset = (list(df_combined_t.index[2:]), list(df_combined_t.columns))).apply(
# lambda x: ["background: #72A4F7" if (i < 1 and v < x.iloc[1]*0.85) else "" for i,v in enumerate(x)], axis = 1,subset = (list(df_combined_t.index[2:]), list(df_combined_t.columns))).apply(
# lambda x: ["background: #72A4F7" if (i == 1 and v < x.iloc[2]*0.85) else "" for i,v in enumerate(x)], axis = 1,subset = (list(df_combined_t.index[2:]), list(df_combined_t.columns))).apply(
# lambda x: ["background: #FBBC04" if (i < 1 and v > x.iloc[1]*1.2) else "" for i,v in enumerate(x)], axis = 1,subset = (list(df_combined_t.index[2:]), list(df_combined_t.columns))).apply(
# lambda x: ["background: #FBBC04" if (i == 1 and v > x.iloc[2]*1.2) else "" for i,v in enumerate(x)], axis = 1,subset = (list(df_combined_t.index[2:]), list(df_combined_t.columns))).apply(
# lambda x: ["color: #ffffff" if (i < 1 and v < x.iloc[1]*0.8) else "" for i,v in enumerate(x)], axis = 1,subset = (list(df_combined_t.index[2:]), list(df_combined_t.columns))).apply(
# lambda x: ["color: #ffffff" if (i == 1 and v < x.iloc[2]*0.8) else "" for i,v in enumerate(x)], axis = 1,subset = (list(df_combined_t.index[2:]), list(df_combined_t.columns))).apply(
# lambda x: ["background: #4285F4" if (i == 0 and v < x.iloc[1]*0.8) else "" for i,v in enumerate(x)], axis = 1,subset = (list(df_combined_t.index[2:]), list(df_combined_t.columns))).apply(
# lambda x: ["background: #4285F4" if (i == 1 and v < x.iloc[2]*0.8) else "" for i,v in enumerate(x)], axis = 1,subset = (list(df_combined_t.index[2:]), list(df_combined_t.columns))).apply(
# lambda x: ["background: #ffffff" if (i == 0 and v == x.iloc[1]) else "" for i,v in enumerate(x)], axis = 1,subset = (list(df_combined_t.index[2:]), list(df_combined_t.columns))).apply(
# lambda x: ["background: #ffffff" if (i == 1 and v == x.iloc[2]) else "" for i,v in enumerate(x)], axis = 1,subset = (list(df_combined_t.index[2:]), list(df_combined_t.columns))).apply(
# lambda x: ["color: #000000" if (i < 1 and v == x.iloc[1]) else "" for i,v in enumerate(x)], axis = 1,subset = (list(df_combined_t.index[2:]), list(df_combined_t.columns))).apply(
# lambda x: ["color: #000000" if (i == 1 and v == x.iloc[2]) else "" for i,v in enumerate(x)], axis = 1,subset = (list(df_combined_t.index[2:]), list(df_combined_t.columns))).format(
# "{:.1%}",subset=(rows[2:],df_combined_t.columns)).format(
# '{:.0f}',subset=(rows[0],df_combined_t.columns)).set_precision(2).set_properties(
# **{'index':'White','min-width':'60px'},overwrite=False)
# #.set_table_styles([index_names, headers])
# df_combined_t_style = df_combined_t_style.format(
# {df_combined_t_style.columns[0]: '{:,.1%}'.format,
# df_combined_t_style.columns[1]: '{:,.1%}'.format,
# df_combined_t_style.columns[2]: '{:,.1%}'.format},subset=(rows[2:],df_combined_t.columns)
# )
# df_combined_t_style = df_combined_t_style.format(
# '{:.0f}',subset=(rows[0],df_combined_t.columns))
# df_combined_t_style
# dfi.export(df_combined_t_style, 'players/'+name+'_'+str(last_games)+'.png',fontsize=9,dpi=600,table_conversion='chrome')
percent_owned = summary_2023_one['percent_owned'].reset_index(drop=True)[0]
yahoo_position = summary_2023_one['display_position'].reset_index(drop=True)[0]
# image = "https://cms.nhl.bamgrid.com/images/headshots/current/168x168/"+str(player_id)+".png"
# logo = nhl_logos[nhl_logos.Team==list(player_games_one['Team'])[0]].reset_index().URL[0]
# fig, ax = plt.subplots(figsize=(10,16))
# fig.set_facecolor('white')
# # img = mpimg.imread('players/'+name+'_'+str(last_games)+'.png')
# # ax.imshow(img)
# # ax.axis('off')
# # fig.tight_layout()
# ax.axis('off')
# im = plt.imread('players/'+name+'_'+str(last_games)+'.png')
# ax = fig.add_axes([0,0,1,0.85], anchor='C', zorder=1)
# ax.imshow(im)
# ax.axis('off')
# fig.tight_layout()
# fig.text(x=0.5,y=-0.05,s='Note: Last Games compares to 2023-24. 2023-24 compares to 2022-23.',horizontalalignment='center',fontsize=16,fontname='Century Gothic')
# # fig.text(x=0.05,y=-0.1,s='Created By: @TJStats',horizontalalignment='left',fontsize=24,fontname='Century Gothic')
# # fig.text(x=0.95,y=-0.1,s='Data: Natural Stat Trick',horizontalalignment='right',fontsize=24,fontname='Century Gothic')
# fig.text(x=0.5,y=1.13,s='NHL Player Summary',horizontalalignment='center',fontsize=52, fontweight='bold')
# fig.text(x=0.5,y=1.08,s='2023-24 Season',horizontalalignment='center',fontsize=36,fontname='Century Gothic', fontstyle='italic')
# fig.text(x=0.12,y=1.03,s='Player',horizontalalignment='center',fontsize=22,fontname='Century Gothic', fontweight='bold')
# fig.text(x=0.12,y=1.0,s='Team',horizontalalignment='center',fontsize=22,fontname='Century Gothic', fontweight='bold')
# fig.text(x=0.12,y=0.97,s='Position',horizontalalignment='center',fontsize=22,fontname='Century Gothic', fontweight='bold')
# #fig.text(x=0.12,y=0.94,s='Age',horizontalalignment='center',fontsize=22,fontname='Century Gothic', fontweight='bold')
# # fig.text(x=0.12,y=0.91,s='Cap Hit',horizontalalignment='center',fontsize=22,fontname='Century Gothic', fontweight='bold')
# #fig.text(x=0.12,y=0.88,s='Roster%',horizontalalignment='center',fontsize=22,fontname='Century Gothic', fontweight='bold')
# fig.text(x=0.25,y=1.03,s=name,horizontalalignment='left',fontsize=22,fontname='Century Gothic')
# fig.text(x=0.25,y=1.0,s=list(player_games_one['Team'])[0],horizontalalignment='left',fontsize=22,fontname='Century Gothic')
# fig.text(x=0.25,y=0.97,s=yahoo_position,horizontalalignment='left',fontsize=22,fontname='Century Gothic')
# #fig.text(x=0.25,y=0.94,s=str(int(summary_2023_one.reset_index().AGE[0])),horizontalalignment='left',fontsize=22,fontname='Century Gothic')
# # fig.text(x=0.25,y=0.91,s=summary_2023_one.loc[summary_2023_one['player_id']==player_id].reset_index()['sheets'][0],horizontalalignment='left',fontsize=22,fontname='Century Gothic')
# #fig.text(x=0.25,y=0.88,s=str(int(percent_owned*100))+'%',horizontalalignment='left',fontsize=22,fontname='Century Gothic')
# im = plt.imread(image)
# newax = fig.add_axes([0.5,0.8,0.22,0.22], anchor='NW', zorder=1)
# newax.imshow(im)
# imr = plt.imread(logo)
# newerax = fig.add_axes([0.75,0.8,0.22,0.22], anchor='NW', zorder=1)
# newerax.imshow(imr)
# newax.axis('off')
# newerax.axis('off')
# plt.savefig('players/'+name+"_"+str(last_games)+' int.png',bbox_inches="tight")
# plt.close()
#test.loc[name == test.Player].reset_index().TOI[0]/1.5
min_time = min(math.floor(summary_2023.loc[player_id == summary_2023.player_id].reset_index().TOI[0]/100)*100,summary_2023.GP.max()*10)
# min_time = min(math.floor(test.loc[name == test.Player].reset_index().TOI[0]/100)*100,test.GP.max()*10)
#summary_2023 = summary_2023.drop_duplicates(subset=['player_id'])
test_filter = summary_2023[(summary_2023.TOI >= min_time)&(summary_2023.pos == summary_2023.loc[player_id == summary_2023.player_id].reset_index().pos[0])]
test_filter['Goals/GP'] = test_filter['Goals']/test_filter['GP']
test_filter['Total Assists/GP'] = test_filter['Assists']/test_filter['GP']
test_filter['Total Points/GP'] = test_filter['Total_Points']/test_filter['GP']
test_filter['PP Points/GP'] = test_filter['Total_Points_pp']/test_filter['GP']
test_filter['Shots/GP'] = test_filter['Shots']/test_filter['GP']
test_filter['Hits/GP'] = test_filter['Hits']/test_filter['GP']
test_filter['Shots Blocked/GP'] = test_filter['Shots_Blocked']/test_filter['GP']
test_filter['ixG/60'] = test_filter['ixG']/test_filter['TOI']*60
test_filter['Goals/60'] = test_filter['Goals']/test_filter['TOI']*60
test_filter['G-xG/60'] = test_filter['G-ixG']/test_filter['TOI']*60
test_filter['iCF/60'] = test_filter['iCF']/test_filter['TOI']*60
test_filter['iSCF/60'] = test_filter['iSCF']/test_filter['TOI']*60
test_filter['First Assists/60'] = test_filter['First_Assists']/test_filter['TOI']*60
test_filter['Total Points/60'] = test_filter['Total_Points']/test_filter['TOI']*60
test_filter['G-xG/60'] = test_filter['Goals/60'] - test_filter['ixG/60']
test_filter['Goals Z-Score'] = (test_filter['Goals/GP']-test_filter['Goals/GP'].mean())/test_filter['Goals/GP'].std()
test_filter['Assists Z-Score'] = (test_filter['Total Assists/GP']-test_filter['Total Assists/GP'].mean())/test_filter['Total Assists/GP'].std()
test_filter['Points Z-Score'] = (test_filter['Total Points/GP']-test_filter['Total Points/GP'].mean())/test_filter['Total Points/GP'].std()
test_filter['PP Points Z-Score'] = (test_filter['PP Points/GP']-test_filter['PP Points/GP'].mean())/test_filter['PP Points/GP'].std()
test_filter['Shots Z-Score'] = (test_filter['Shots/GP']-test_filter['Shots/GP'].mean())/test_filter['Shots/GP'].std()
test_filter['Hits Z-Score'] = (test_filter['Hits/GP']-test_filter['Hits/GP'].mean())/test_filter['Hits/GP'].std()
test_filter['Blocks Z-Score'] = (test_filter['Shots Blocked/GP']-test_filter['Shots Blocked/GP'].mean())/test_filter['Shots Blocked/GP'].std()
test_filter['ixG Z-Score'] = (test_filter['ixG/60']-test_filter['ixG/60'].mean())/test_filter['ixG/60'].std()
test_filter['G Z-Score'] = (test_filter['Goals/60']-test_filter['Goals/60'].mean())/test_filter['Goals/60'].std()
test_filter['G-xG Z-Score'] = (test_filter['G-xG/60']-test_filter['G-xG/60'].mean())/test_filter['G-xG/60'].std()
test_filter['iCF Z-Score'] = (test_filter['iCF/60']-test_filter['iCF/60'].mean())/test_filter['iCF/60'].std()
test_filter['iSCF Z-Score'] = (test_filter['iSCF/60']-test_filter['iSCF/60'].mean())/test_filter['iSCF/60'].std()
test_filter['First Assists Z-Score'] = (test_filter['First Assists/60']-test_filter['First Assists/60'].mean())/test_filter['First Assists/60'].std()
test_filter['P Z-Score'] = (test_filter['Total Points/60']-test_filter['Total Points/60'].mean())/test_filter['Total Points/60'].std()
values_1 = test_filter.loc[player_id == test_filter.player_id][['Goals/GP','Total Assists/GP','Total Points/GP','PP Points/GP','Shots/GP','Hits/GP','Shots Blocked/GP']].reset_index(drop=True).loc[0]
values_2 = test_filter.loc[player_id == test_filter.player_id][['ixG/60','Goals/60','G-xG/60','iCF/60','iSCF/60','First Assists/60','Total Points/60']].reset_index(drop=True).loc[0]
categories = [i[:-11]+'/GP' for i in test_filter.columns[-14:-7]]
#categories = [*categories]
player = list(np.around(test_filter.loc[player_id == test_filter.player_id][test_filter.columns[-14:-7]].values.flatten().tolist()))
#player = [*player, player[0]]
label_loc = np.linspace(start=0, stop=2 * np.pi, num=len(player))
players_stats_all_on_filter = test_filter.copy()
players_stats_all_on_filter['GF/60'] = (players_stats_all_on_filter['GF'])/players_stats_all_on_filter['TOI']*60
players_stats_all_on_filter['xGF/60'] = (players_stats_all_on_filter['xGF'])/players_stats_all_on_filter['TOI']*60
players_stats_all_on_filter['CF/60'] = (players_stats_all_on_filter['CF'])/players_stats_all_on_filter['TOI']*60
# players_stats_all_on_filter['oiSH%'] = (players_stats_all_on_filter['On-Ice SH%']-players_stats_all_on_filter['On-Ice SH%'].mean())/players_stats_all_on_filter['On-Ice SH%'].std()
#players_stats_all_on_filter['OZ Start%'] = (players_stats_all_on_filter['CF']-players_stats_all_on_filter['CF'])/players_stats_all_on_filter['CF']
players_stats_all_on_filter['GF Z-Score'] = (players_stats_all_on_filter['GF/60']-players_stats_all_on_filter['GF/60'].mean())/players_stats_all_on_filter['GF/60'].std()
players_stats_all_on_filter['xGF Z-Score'] = (players_stats_all_on_filter['xGF/60']-players_stats_all_on_filter['xGF/60'].mean())/players_stats_all_on_filter['xGF/60'].std()
players_stats_all_on_filter['CF Z-Score'] = (players_stats_all_on_filter['CF/60']-players_stats_all_on_filter['CF/60'].mean())/players_stats_all_on_filter['CF/60'].std()
players_stats_all_on_filter['oiSH% Z-Score'] = (players_stats_all_on_filter['oiSH']-players_stats_all_on_filter['oiSH'].mean())/players_stats_all_on_filter['oiSH'].std()
players_stats_all_on_filter['OZ Start% Z-Score'] = (players_stats_all_on_filter['OZ Start%']-players_stats_all_on_filter['OZ Start%'].mean())/players_stats_all_on_filter['OZ Start%'].std()
categories_on = [i[:-8]+'/60' for i in players_stats_all_on_filter.columns[-5:]]
categories_on = ['GF/60', 'xGF/60', 'CF/60', 'oiSH', 'OZ Start%']
player_on = list(np.around(players_stats_all_on_filter.loc[player_id == test_filter.player_id][players_stats_all_on_filter.columns[-5:]].values.flatten().tolist(),2))
categories_1 = [i[:-8]+'/GP' for i in test_filter.columns[-14:-7]]
categories_2 = [i[:-8]+'/60' for i in test_filter.columns[-7:]]
categories = categories_1+categories_2
categories[12] = '1A/60'
player = list(np.around(test_filter.loc[player_id == test_filter.player_id][test_filter.columns[-14:]].values.flatten().tolist(),2))
# color_scheme = []
# for i in player:
# if i <= -2:
# color_scheme.append('#4285F4')
# if i > -2 and i <= -1:
# color_scheme.append('#A1C2FA')
# if i > -1 and i <= 0:
# color_scheme.append('#D0E1FD')
# if i > 0 and i <= 1:
# color_scheme.append('#FEEFC1')
# if i > 1 and i <= 2:
# color_scheme.append('#FDDE82')
# if i > 2:
# color_scheme.append('#FBBC04')
goals_above_expected = test_filter.loc[player_id == test_filter.player_id]['Goals'] - test_filter.loc[player_id == test_filter.player_id]['ixG']
goals_above_expected = test_filter.loc[player_id == test_filter.player_id]['Goals'] - test_filter.loc[player_id == test_filter.player_id]['ixG']
# color_scheme_on= []
# for i in player_on:
# if i <= -2:
# color_scheme_on.append('#4285F4')
# if i > -2 and i <= -1:
# color_scheme_on.append('#A1C2FA')
# if i > -1 and i <= 0:
# color_scheme_on.append('#D0E1FD')
# if i > 0 and i <= 1:
# color_scheme_on.append('#FEEFC1')
# if i > 1 and i <= 2:
# color_scheme_on.append('#FDDE82')
# if i > 2:
# color_scheme_on.append('#FBBC04')
fig = plt.figure(figsize=(24, 13.5),dpi=300)
fig.set_facecolor('white')
cmap_new = matplotlib.colors.LinearSegmentedColormap.from_list("", ["#4285F4","white",'#FBBC04'])
colormap_new = plt.get_cmap(cmap_new)
norm_new = Normalize(vmin=-3, vmax=3)
color_scheme = [colormap_new(norm_new(x)) for x in player]
color_scheme_on = [colormap_new(norm_new(x)) for x in player_on]
players_stats_all_on_filter = players_stats_all_on_filter.rename(columns={'On-Ice SH%':'oiSH%','Off.\xa0Zone Start %':'OZ Start%'})
values_on = players_stats_all_on_filter.loc[player_id == test_filter.player_id][['GF/60', 'xGF/60', 'CF/60', 'oiSH', 'OZ Start%']].reset_index(drop=True).loc[0]
position_player = summary_2023_one['pos'].reset_index().pos[0]
rank_1 = list(test_filter[values_1.index].rank(method='min',ascending=False).loc[player_id == test_filter.player_id].reset_index(drop=True).astype(int).iloc[0])
rank_2 = list(test_filter[values_2.index].rank(method='min',ascending=False).loc[player_id == test_filter.player_id].reset_index(drop=True).astype(int).iloc[0])
rank_3 = list(players_stats_all_on_filter[values_on.index].rank(method='min',ascending=False).loc[player_id == test_filter.player_id].reset_index(drop=True).astype(int).iloc[0][categories_on])
#rank_3 = rank_3 + list(players_stats_all_on_filter[values_on.index].rank(method='first',ascending=True).loc[player_id == test.player_id].reset_index(drop=False).astype(int).iloc[0][categories_on[3:5]])
values_on = [float(x) for x in values_on]
player_games_one = player_games_one.merge(right=team_games[['Team','pp_toi','date']],left_on=['Team','date'],right_on=['Team','date'],how='left').fillna(0)
y=(player_games_one.rolling(last_games).sum()['TOI_pp']/player_games_one.rolling(last_games).sum()['pp_toi'])[last_games:]
player_games_one = player_games_one.sort_values(by='date').reset_index(drop=True)
# fig, ([ax1,ax2],[ax3,ax4])= plt.subplots(nrows=2, ncols=2,figsize=(16,10))
colormap = plt.get_cmap(cmap)
value = 1
# Normalize the value
norm = Normalize(vmin=0.8, vmax=1.2)
normalized_value = norm(value)
col_3_colour = ['white']*len(df_combined_t)
col_2_colour = [colormap(norm(x)) for x in list(((df_combined_t[df_combined_t.columns[1]].values) / (df_combined_t[df_combined_t.columns[2]].values)))]
col_1_colour = [colormap(norm(x)) for x in list(((df_combined_t[df_combined_t.columns[0]].values) / (df_combined_t[df_combined_t.columns[1]].values)))]
colour_df = pd.DataFrame(data=[col_1_colour,col_2_colour,col_3_colour]).T.values
if df_combined_t[df_combined_t.columns[2]].values[0] == 0:
for i in range(len(colour_df)):
colour_df[[i],[1]] = 'white'
colour_df[[0],[0]] = 'white'
colour_df[[1],[0]] = 'white'
colour_df[[0],[1]] = 'white'
colour_df[[1],[1]] = 'white'
if df_combined_t.values[[10],[0]] < 0 and df_combined_t.values[[10],[1]] < 0:
cmap_flip = matplotlib.colors.LinearSegmentedColormap.from_list("", ["#FBBC04","white","#4285F4"])
norm = Normalize(vmin=0.8, vmax=1.2)
colour_df[[10],[0]] = tuple(cmap_flip(norm(df_combined_t.values[[10],[0]] / df_combined_t.values[[10],[1]])))
elif df_combined_t.values[[10],[0]] < 0 and df_combined_t.values[[10],[1]] > 0:
#cmap_flip = matplotlib.colors.LinearSegmentedColormap.from_list("", ["#FBBC04","white","#4285F4"])
cmap_y = matplotlib.colors.LinearSegmentedColormap.from_list("", ["white","#4285F4"])
norm = Normalize(vmin=-1, vmax=0)
colour_df[[10],[0]] = tuple(cmap_y(norm(df_combined_t.values[[10],[0]] - df_combined_t.values[[10],[1]])))
elif df_combined_t.values[[10],[0]] > 0 and df_combined_t.values[[10],[1]] < 0:
cmap_y = matplotlib.colors.LinearSegmentedColormap.from_list("", ["white","#FBBC04"])
norm = Normalize(vmin=0, vmax=1)
colour_df[[10],[0]] = tuple(cmap_y(norm(df_combined_t.values[[10],[0]] - df_combined_t.values[[10],[1]])))
if df_combined_t.values[[10],[1]] < 0 and df_combined_t.values[[10],[2]] < 0:
cmap_flip = matplotlib.colors.LinearSegmentedColormap.from_list("", ["#FBBC04","white","#4285F4"])
norm = Normalize(vmin=0.8, vmax=1.2)
colour_df[[10],[1]] = tuple(cmap_flip(norm(df_combined_t.values[[10],[1]] / df_combined_t.values[[10],[2]])))
elif df_combined_t.values[[10],[1]] < 0 and df_combined_t.values[[10],[2]] > 0:
#cmap_flip = matplotlib.colors.LinearSegmentedColormap.from_list("", ["#FBBC04","white","#4285F4"])
cmap_y = matplotlib.colors.LinearSegmentedColormap.from_list("", ["white","#4285F4"])
norm = Normalize(vmin=-1, vmax=0)
colour_df[[10],[1]] = tuple(cmap_y(norm(df_combined_t.values[[10],[1]] - df_combined_t.values[[10],[2]])))
elif df_combined_t.values[[10],[1]] > 0 and df_combined_t.values[[10],[2]] < 0:
cmap_y = matplotlib.colors.LinearSegmentedColormap.from_list("", ["white","#FBBC04"])
norm = Normalize(vmin=0, vmax=1)
colour_df[[10],[1]] = tuple(cmap_y(norm(df_combined_t.values[[10],[1]] - df_combined_t.values[[10],[2]])))
ax1 = plt.subplot(1,3,1)
ax2 = plt.subplot(3,3,2)
ax3 = plt.subplot(3,3,5)
ax4 = plt.subplot(3,3,8)
ax5 = plt.subplot(3,3,3)
ax6 = plt.subplot(3,3,6)
ax7 = plt.subplot(3,3,9)
#axbot = plt.subplot(3,1,1)
axes = [ax1, ax2, ax3, ax4, ax5,ax6,ax7]
# ax[0][0].axis('off')
# im = plt.imread('players/'+name+'_'+str(last_games)+' int.png')
# ax[0][0] = fig.add_axes([0,0,1,1], anchor='W', zorder=1)
# ax[0][0].imshow(im)
# try:
# #image = "https://cms.nhl.bamgrid.com/images/headshots/current/168x168/"+str(player_id)+".png"
# image = "https://assets.nhle.com/mugs/nhl/20232024/PIT/"+str(player_id)+".png"
# im = plt.imread(image)
# except HTTPError as err:
# if err.code == 403:
# image = "https://cms.nhl.bamgrid.com/images/headshots/current/168x168/skater.png"
# im = plt.imread(image)
# else:
# raise
#logo = nhl_logos[nhl_logos.Team==list(player_games_one['Team'])[0]].reset_index().URL[0]
#im = plt.imread('players/'+name+'_'+str(last_games)+'.png')
#ax = fig.add_axes([0,0,1,0.85], anchor='C', zorder=1)
#ax.imshow(im)
#index_player = player_id
try:
image = requests.get(f"https://api-web.nhle.com/v1/player/{player_id}/landing/").json()['headshot']
#image = "https://cms.nhl.bamgrid.com/images/headshots/current/168x168/"+str(index_player)+".png"
im = plt.imread(image)
except HTTPError as err:
if err.code == 403:
image = "https://cms.nhl.bamgrid.com/images/headshots/current/168x168/skater.png"
image = "https://assets.nhle.com/mugs/nhl/default-skater.png"
im = plt.imread(image)
else:
raise
try:
logo = nhl_logos[nhl_logos.Team==list(player_games_one['Team'])[0]].reset_index().URL[0]
except KeyError:
logo = 'https://a.espncdn.com/combiner/i?img=/i/teamlogos/leagues/500/nhl.png&w=1000&h=1000'
#im = plt.imread(image)
im = OffsetImage(im, zoom=.33)
ab = AnnotationBbox(im, (0.69, 0.765), xycoords='axes fraction', box_alignment=(0.0,0.0),bboxprops={'edgecolor':'white'})
ax1.add_artist(ab)
#axim = fig.add_axes([0.25,0.76,0.12,0.12], anchor='NW', zorder=1)
#axim.imshow(im)
#axim.axis('off')
imr = plt.imread(logo)
imr = OffsetImage(imr, zoom=.1)
ab = AnnotationBbox(imr, (0.45, 0.765), xycoords='axes fraction', box_alignment=(0.0,0.0),bboxprops={'edgecolor':'white'})
ax1.add_artist(ab)
# axim = fig.add_axes([0.18,0.76,0.75,0.075], anchor='NW', zorder=1)
# axim.imshow(imr)
# axim.axis('off')
sub_value = 0.16
ax1.text(x=0.5,y=1.13-sub_value,s='NHL Player Summary',horizontalalignment='center',fontsize=36, fontweight='bold')
ax1.text(x=0.5,y=1.08-sub_value,s='2024-25 Season',horizontalalignment='center',fontsize=28,fontname='Century Gothic', fontstyle='italic')
ax1.text(x=0.05,y=1.04-sub_value,s='Player',horizontalalignment='center',fontsize=18,fontname='Century Gothic', fontweight='bold')
ax1.text(x=0.05,y=1.005-sub_value,s='Team',horizontalalignment='center',fontsize=18,fontname='Century Gothic', fontweight='bold')
ax1.text(x=0.05,y=0.97-sub_value,s='Position',horizontalalignment='center',fontsize=18,fontname='Century Gothic', fontweight='bold')
#ax1.text(x=0.1,y=0.94-sub_value,s='Age',horizontalalignment='center',fontsize=18,fontname='Century Gothic', fontweight='bold')
#ax1.text(x=0.12,y=0.91-sub_value,s='Cap Hit',horizontalalignment='center',fontsize=22,fontname='Century Gothic', fontweight='bold')
ax1.text(x=0.05,y=0.935-sub_value,s='Roster%',horizontalalignment='center',fontsize=18,fontname='Century Gothic', fontweight='bold')
ax1.text(x=0.175,y=1.04-sub_value,s=name,horizontalalignment='left',fontsize=18,fontname='Century Gothic')
ax1.text(x=0.175,y=1.005-sub_value,s=list(player_games_one['Team'])[0],horizontalalignment='left',fontsize=18,fontname='Century Gothic')
ax1.text(x=0.175,y=0.97-sub_value,s=yahoo_position,horizontalalignment='left',fontsize=18,fontname='Century Gothic')
#ax1.text(x=0.25,y=0.94-sub_value,s=str(summary_2023_one.reset_index().AGE[0]),horizontalalignment='left',fontsize=22,fontname='Century Gothic')
#ax1.text(x=0.25,y=0.91-sub_value,s=summary_2023_one.loc[summary_2023_one['player_id']==player_id].reset_index()['sheets'][0],horizontalalignment='left',fontsize=22,fontname='Century Gothic')
ax1.text(x=0.175,y=0.935-sub_value,s=str(int(percent_owned*100))+'%',horizontalalignment='left',fontsize=18,fontname='Century Gothic')
ax1.axis("off")
table = ax1.table(cellText=df_combined_t.values, colLabels=df_combined_t.columns,rowLabels=df_combined_t.index
, cellLoc='center',rowLoc='center', bbox=[0.15, 0.05, 0.8, 0.7],cellColours=colour_df)
#table.auto_set_font_size(True)
table.set_fontsize(20)
table.scale(1, 1.5)
format_col = df_combined_t[df_combined_t.columns[0]]
n_c = 0
for cell in table.get_celld().values():
if n_c < 1*3:
if cell.get_text().get_text() in format_col.astype(str).values:
cell.get_text().set_text('{:,.0f}'.format(float(cell.get_text().get_text())))
elif n_c < 16*3:
if cell.get_text().get_text() in format_col.astype(str).values:
cell.get_text().set_text('{:,.2f}'.format(float(cell.get_text().get_text())))
else:
if cell.get_text().get_text() in format_col.astype(str).values:
cell.get_text().set_text('{:,.1%}'.format(float(cell.get_text().get_text())))
n_c = n_c + 1
format_col = df_combined_t[df_combined_t.columns[1]]
n_c = 0
for cell in table.get_celld().values():
if n_c < 1*3:
if cell.get_text().get_text() in format_col.astype(str).values:
cell.get_text().set_text('{:,.0f}'.format(float(cell.get_text().get_text())))
elif n_c < 16*3:
if cell.get_text().get_text() in format_col.astype(str).values:
cell.get_text().set_text('{:,.2f}'.format(float(cell.get_text().get_text())))
else:
if cell.get_text().get_text() in format_col.astype(str).values:
cell.get_text().set_text('{:,.1%}'.format(float(cell.get_text().get_text())))
n_c = n_c + 1
format_col = df_combined_t[df_combined_t.columns[2]]
n_c = 0
for cell in table.get_celld().values():
if n_c < 1*3:
if cell.get_text().get_text() in format_col.astype(str).values:
cell.get_text().set_text('{:,.0f}'.format(float(cell.get_text().get_text())))
elif n_c < 16*3:
if cell.get_text().get_text() in format_col.astype(str).values:
cell.get_text().set_text('{:,.2f}'.format(float(cell.get_text().get_text())))
else:
if cell.get_text().get_text() in format_col.astype(str).values:
cell.get_text().set_text('{:,.1%}'.format(float(cell.get_text().get_text())))
n_c = n_c + 1
#ax1.text('')
# ax1.axis('off')
# img = mpimg.imread('players/'+name+'_'+str(last_games)+' int.png')
# im = plt.imread('players/'+name+'_'+str(last_games)+'.png')
# ax1 = fig.add_axes([0.03,0.,1,1], anchor='SW')
# ax1.imshow(im)
# ax1.imshow(img)
# ax1.axis('off')
# fig.tight_layout()
categories[0:7] = ['G/GP','A/GP','P/GP','PPP/GP','S/GP','Hits/GP','Blk/GP']
_ = sns.barplot(data=test_filter[test_filter.columns[56:63]],x=categories[0:7],y=player[0:7],palette=color_scheme[0:7],edgecolor='black',ax=ax2)
ax2.set_title(f"Individual Per Game Z-Score (vs {position_player}, min. {min_time:.0f} TOI)",fontsize=14,fontname='Century Gothic')
#plt.rcParams['xtick.color']='#333F4B'
#ax[0][1].set_prop_cycle(ytick.color='#333F4B')
ax2.set_ylabel('Z-Score', fontsize=15,fontname='Century Gothic')
#plt.ylabel('Z-Score', fontsize=15,fontname='Century Gothic')
#plt.xlabel('Percentile', fontsize=12, color = '#000000',fontname='Century Gothic')
#plt.tick_params(axis='x', which='both', labelsize=10,bottom=False,top=False)
ax2.set_ylim([-3, 3])
plt.style.use('classic')
show_values(ax2,stat = values_1,rank_n=rank_1)
ax2.grid(axis = 'y',linestyle = '-', linewidth = 0.5,alpha=0.3)
ax2.set_axisbelow(True)
#ax[1].hlines(y=0,xmin=0,xmax=len(player),color='black')
#plt.savefig('players/'+name+"_"+str(last_games)+'_Z.png')#,bbox_inches="tight")
# ax[1][0] = sns.barplot(data=test,x=categories,y=player,palette=color_scheme,edgecolor='black')
# show_values(ax2,stat = values)
# data_input = df_shots[(df_shots.shooterName==name) & (df_shots.event!='MISS')]
# sns.kdeplot(data=data_input, x=data_input["yCordAdjusted"]*-1, y=data_input["xCordAdjusted"],fill=True,thresh=0.4,cmap=cmap,ax=ax3)
# #sns.scatterplot(data=data_input, x=data_input["yCordAdjusted"]*-1, y=data_input["xCordAdjusted"], alpha=1,zorder=25,cmap='Blues',s=400,hue='shotType',palette="Set2")
# rink = NHLRink(rotation=270)
# #x, y = rink.convert_xy(x, y)
# rink.draw(ax=ax3,display_range='dzone')
# ax3.set_title(name+" Shooting Heat Map",fontsize=16,fontname='Century Gothic')
#plt.suptitle('NHL Shot Locations ', fontsize=32, y = 0.91)
#plt.title('All Shots', fontsize=16, y=1.02)
sns.barplot(x=categories[7:14],y=player[7:14],palette=color_scheme[7:14],edgecolor='black',ax=ax3)
ax3.set_title(f"Individual Rate Z-Score (vs {position_player}, min. {min_time:.0f} TOI)",fontsize=14,fontname='Century Gothic')
ax3.grid(axis = 'y',linestyle = '-', linewidth = 0.5,alpha=0.3)
ax3.set_ylim([-3, 3])
ax3.set_axisbelow(True)
ax3.set_ylabel('Z-Score', fontsize=15,fontname='Century Gothic')
#plt.rcParams['xtick.color']='#333F4B'
#ax[0][1].set_prop_cycle(ytick.color='#333F4B')
sns.barplot(x=categories_on,y=player_on,palette=color_scheme_on,edgecolor='black',ax=ax4)
ax4.set_ylim([-3, 3])
ax4.set_title(f"On-Ice All Situations Rate Z-Score (vs {position_player}, min. {min_time:.0f} TOI)",fontsize=14,fontname='Century Gothic')
ax4.set_axisbelow(True)
ax4.set_ylabel('Z-Score', fontsize=15,fontname='Century Gothic')
ax4.grid(axis = 'y',linestyle = '-', linewidth = 0.5,alpha=0.3)
ax2.set_ylabel('Z-Score', fontsize=15,fontname='Century Gothic')
show_values(ax3,stat = values_2,rank_n=rank_2)
values_on[3] = str(round(values_on[3]*100,1))+'%'
values_on[4] = str(round(values_on[4]*100,1))+'%'
show_values(ax4,stat = values_on,rank_n=rank_3)
ax2.text(-0.5, -3.8, '2024-25', ha="right",fontstyle='italic',zorder=1)
ax3.text(-0.5, -3.8, '2024-25', ha="right",fontstyle='italic')
ax4.text(-0.5, -3.8, '2024-25', ha="right",fontstyle='italic')
ax2.text(-0.5, -4.2, 'Rank (of '+str(len(test_filter))+")", ha="right",fontstyle='italic',zorder=100)
ax3.text(-0.5, -4.2, 'Rank (of '+str(len(test_filter))+")", ha="right",fontstyle='italic',zorder=100)
ax4.text(-0.5, -4.2, 'Rank (of '+str(len(test_filter))+")", ha="right",fontstyle='italic',zorder=100)
ax2.tick_params(axis='x', which='both', labelsize=12,bottom=False,top=False)
ax3.tick_params(axis='x', which='both', labelsize=12,bottom=False,top=False)
ax4.tick_params(axis='x', which='both', labelsize=12,bottom=False,top=False)
if summary_2023_one.GP.values[0] < 2:
line_text_value = 1
else:
line_text_value = last_games+0.5
if position_player == 'F':
ax5.hlines(y=18,xmin=0, xmax=100, color='black',linewidth=1,linestyles='--',alpha=0.5)
ax5.text(s="1st",y=18,x=line_text_value, color='black',fontsize=8,bbox=dict(facecolor='white', alpha=0.5, pad=1.0))
ax5.hlines(y=16,xmin=0, xmax=100, color='black',linewidth=1,linestyles='--',alpha=0.5)
ax5.text(s="2nd",y=16,x=line_text_value, color='black',fontsize=8,bbox=dict(facecolor='white', alpha=0.5, pad=1.0))
ax5.hlines(y=14,xmin=0, xmax=100, color='black',linewidth=1,linestyles='--',alpha=0.5)
ax5.text(s="3rd",y=14,x=line_text_value, color='black',fontsize=8,bbox=dict(facecolor='white', alpha=0.5, pad=1.0))
ax5.hlines(y=12,xmin=0, xmax=100, color='black',linewidth=1,linestyles='--',alpha=0.5)
ax5.text(s="4th",y=12,x=line_text_value, color='black',fontsize=8,bbox=dict(facecolor='white', alpha=0.5, pad=1.0))
if position_player == 'D':
ax5.hlines(y=23,xmin=0, xmax=100, color='black',linewidth=1,linestyles='--',alpha=0.5)
ax5.text(s="1st",y=23,x=line_text_value, color='black',fontsize=8,bbox=dict(facecolor='white', alpha=0.5, pad=1.0))
ax5.hlines(y=20,xmin=0, xmax=100, color='black',linewidth=1,linestyles='--',alpha=0.5)
ax5.text(s="2nd",y=20,x=line_text_value, color='black',fontsize=8,bbox=dict(facecolor='white', alpha=0.5, pad=1.0))
ax5.hlines(y=17,xmin=0, xmax=100, color='black',linewidth=1,linestyles='--',alpha=0.5)
ax5.text(s="3rd",y=17,x=line_text_value, color='black',fontsize=8,bbox=dict(facecolor='white', alpha=0.5, pad=1.0))
sns.lineplot(x=player_games_one.game,y=player_games_one.rolling(last_games,min_periods=last_games).mean()['TOI'],ax=ax5,color='#FFB000',linewidth = 2,label='TOI/GP',legend=False)
ax5.xaxis.set_major_locator(MaxNLocator(integer=True))
ax5.set_xlim([last_games, np.max(player_games_one.game)])
axn = ax5.twinx()
#sns.lineplot(x=game_log_pp.Game,y=game_log_pp.rolling(last_games).mean()['PP_TOI'],ax=axn,color='#DCAD23',linewidth = 2,label='PP TOI/GP',legend=False)
#ax5.set_ylim([min(math.floor(min(player_games_one.TOI)/5)*5,10), math.ceil(max((player_games_one.rolling(last_games).mean().fillna(0)['TOI']))/5)*5])
ax5.set_ylim([10,30])
ax5.grid(axis = 'x',linestyle = '-', linewidth = 0.5,alpha=0.3)
ax5.grid(axis = 'y',linestyle = '-', linewidth = 0.5,alpha=0.3)
ax5.set_title(str(last_games)+" Game Rolling Average - TOI and PP%",fontsize=14,fontname='Century Gothic')
ax5.set(xlabel='Game', ylabel='TOI/GP')
axn.set(xlabel='Game', ylabel='PP%')
axn.yaxis.set_major_formatter(mtick.PercentFormatter(1.0))
axn.set_ylim([0, 1])
sns.lineplot(x=player_games_one.game,y=(player_games_one.rolling(last_games).sum()['TOI_pp']/player_games_one.rolling(last_games).sum()['pp_toi']),ax=axn,color='#648FFF',linewidth = 2,label='PP%',legend=False)
#
handles, labels = [ax5.get_legend_handles_labels()[0]+axn.get_legend_handles_labels()[0]]+[ax5.get_legend_handles_labels()[1]+axn.get_legend_handles_labels()[1]]
ax5.legend(handles, labels, fontsize=10,ncol=2,loc=9)
sns.lineplot(x=player_games_one.game,y=player_games_one.rolling(last_games).mean()['Total Points'],ax=ax6,color='#FFB000',label='Points',linewidth = 2)
sns.lineplot(x=player_games_one.game,y=player_games_one.rolling(last_games).mean()['Total Points_pp'],ax=ax6,color='#648FFF',label='PP Points',linewidth = 2)
sns.lineplot(x=player_games_one.game,y=player_games_one.rolling(last_games).mean()['Goals'],ax=ax6,color='#DC267F',label='Goals',linewidth = 2)
sns.lineplot(x=player_games_one.game,y=player_games_one.rolling(last_games).mean()['Total Assists'],ax=ax6,color='#FE6100',label='Assists',linewidth = 2)
ax6.legend(fontsize=10,ncol=4,loc=9)
ax6.xaxis.set_major_locator(MaxNLocator(integer=True))
ax6.set_xlim([last_games, np.max(player_games_one.game)])
ax6.set_ylim([0, round(max((player_games_one.rolling(last_games).mean().fillna(0)['Total Points'])+1)*2)/2])
ax6.grid(axis = 'x',linestyle = '-', linewidth = 0.5,alpha=0.3)
ax6.grid(axis = 'y',linestyle = '-', linewidth = 0.5,alpha=0.3)
ax6.set_title(str(last_games)+" Game Rolling Average - Points",fontsize=14)
ax6.set(xlabel='Game', ylabel='Value Per Game')
sns.lineplot(x=player_games_one.game,y=player_games_one.rolling(last_games).mean()['Shots'],ax=ax7,color='#FFB000',linewidth = 2,label='Shots')
sns.lineplot(x=player_games_one.game,y=player_games_one.rolling(last_games).mean()['iCF'],ax=ax7,color='#648FFF',linewidth = 2,label='iCF')
# sns.lineplot(x=player_games_one.game,y=player_games_one.rolling(last_games).mean()['iSCF'],ax=ax7,color='#DC267F',linewidth = 2,label='iSCF')
sns.lineplot(x=player_games_one.game,y=player_games_one.rolling(last_games).mean()['Hits'],ax=ax7,color='#DC267F',linewidth = 2,label='Hits')
sns.lineplot(x=player_games_one.game,y=player_games_one.rolling(last_games).mean()['Shots Blocked'],ax=ax7,color="#FE6100",linewidth = 2,label='Blocks')
ax7.legend(fontsize=10,ncol=5,loc=9)
ax7.xaxis.set_major_locator(MaxNLocator(integer=True))
ax7.set_xlim([last_games, np.max(player_games_one.game)])
ax7.set_ylim([0, max(round(max((player_games_one.rolling(last_games).mean().fillna(0)['iCF'])+1)*2)/2+1,round(max((player_games_one.rolling(last_games).mean().fillna(0)['Shots'])+1)*2)/2+1,round(max((player_games_one.rolling(last_games).mean().fillna(0)['Hits'])+1)*2)/2+1,round(max((player_games_one.rolling(last_games).mean().fillna(0)['Shots Blocked'])+1)*2)/2+1)])
ax7.grid(axis = 'x',linestyle = '-', linewidth = 0.5,alpha=0.3)
ax7.grid(axis = 'y',linestyle = '-', linewidth = 0.5,alpha=0.3)
ax7.set_title(str(last_games)+" Game Rolling Average - Shots and Bangers",fontsize=14,fontname='Century Gothic')
ax7.set(xlabel='Game', ylabel='Value Per Game')
ax2.hlines(y=0,xmin=-0.5, xmax=len(ax2.patches)-0.5, color='black',linewidth=1)
ax3.hlines(y=0,xmin=-0.5, xmax=len(ax3.patches)-0.5, color='black',linewidth=1)
ax4.hlines(y=0,xmin=-0.5, xmax=len(ax4.patches)-0.5, color='black',linewidth=1)
ax2.set_xlim([-0.5, len(ax2.patches)-0.5])
ax3.set_xlim([-0.5, len(ax3.patches)-0.5])
ax4.set_xlim([-0.5, len(ax4.patches)-0.5])
#plt.tight_layout(pad=5, w_pad=2, h_pad=2)
#abot = fig.add_axes([0.075,0.025,0.9,0.025], anchor='NW', zorder=1)
print('here')
ax1.text(x=0.0,y=-0.025,s='Created By: @TJStats',horizontalalignment='left',fontsize=14)#,fontname='Century Gothic')
ax1.text(x=0.0,y=-0.05,s='Data: Natural Stat Trick, CapFriendly, Yahoo Fantasy',horizontalalignment='left',fontsize=14)#,fontname='Century Gothic')
ax1.text(x=0.725,y=-0.025,s=f'Generated: {str(date.today())}',horizontalalignment='right',fontsize=14)#,fontname='Century Gothic')
from matplotlib.font_manager import FontProperties
font_properties_label = FontProperties(family='century gothic', size=16)
ax5.set_xlabel(xlabel=ax5.get_xlabel(),fontproperties=font_properties_label)
ax6.set_xlabel(xlabel=ax6.get_xlabel(),fontproperties=font_properties_label)
ax7.set_xlabel(xlabel=ax7.get_xlabel(),fontproperties=font_properties_label)
ax5.set_ylabel(ylabel=ax5.get_ylabel(),fontproperties=font_properties_label)
ax6.set_ylabel(ylabel=ax6.get_ylabel(),fontproperties=font_properties_label)
ax7.set_ylabel(ylabel=ax7.get_ylabel(),fontproperties=font_properties_label)
font_properties_title = FontProperties(family='century gothic', size=16)
ax2.set_title(label=ax2.get_title(),fontproperties=font_properties_title)
ax3.set_title(label=ax3.get_title(),fontproperties=font_properties_title)
ax4.set_title(label=ax4.get_title(),fontproperties=font_properties_title)
ax5.set_title(label=ax5.get_title(),fontproperties=font_properties_title)
ax6.set_title(label=ax6.get_title(),fontproperties=font_properties_title)
ax7.set_title(label=ax7.get_title(),fontproperties=font_properties_title)
ax1.text(x=0.43,y=0.025,s='Note: Last Games compares to 2024-25. 2024-25 compares to 2024-25.',horizontalalignment='center',fontsize=12,fontname='Century Gothic')
# font_properties_ticks = FontProperties(family='century gothic', size=12)
# ax5.set_xticklabels(ax5.get_xticks(),fontproperties=font_properties_label)
#plt.xticks(fontname = 'century gothic')
for key, cell in table.get_celld().items():
cell.set_linewidth(0)
#abot.axis('off')
#ax1.set_zorder(2)
fig.tight_layout()
# for i in range(0,len(df_combined_t.index)):
# ax1.text(s=df_combined_t.index[i],x=10,y=700+(10*i),fontsize=10,bbox=dict(facecolor='red', alpha=1))
# #plt.figure(dpi=300)
# if not os.path.exists('player_cards/skaters/'+name):
# os.makedirs('player_cards/skaters/'+name)
# dir = 'players/'
# for f in os.listdir(dir):
# os.remove(os.path.join(dir, f))
#plt.savefig('player_cards/skaters/'+name+'/'+name+"_"+str(last_games)+'_Znew.png',dpi=600,bbox_inches="tight")
#matplotlib.rcParams["figure.dpi"] = 600
#plt.savefig('players/'+name+"_"+str(last_games)+'_Znew.png',dpi=600,bbox_inches="tight")
# test = test.fillna(0)
#test['PP TOI'] = ["%d:%02d" % (int(x),(x*60)%60) if x>0 else '0:00' for x in test['PP TOI']]
app = App(app_ui, server)
#time.sleep(60) |