Spaces:
Sleeping
Sleeping
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=[],linewidth=2,fontsize=10): | |
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()) | |
value_stat = '{:.2f}'.format(float(stat[i])) | |
rank = rank_n[i] | |
ax.text(_x, -4.2, value_stat, ha="center",fontstyle='italic',fontsize=10) | |
ax.text(_x, -4.7, rank, ha="center",fontstyle='italic',fontsize=10) | |
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",fontsize=10) | |
if isinstance(axs, np.ndarray): | |
for idx, ax in np.ndenumerate(axs): | |
_single(ax) | |
else: | |
_single(axs) | |
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", ["#4285F4","white","#FBBC04"]) | |
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 = df_2023[df_2023['display_position']=='G'].reset_index(drop=True) | |
df_2023['pos_new'] = 'G' | |
player_games = pd.read_csv('player_games_goalies.csv',index_col=[0]) | |
summary_2023 = pd.read_csv('summary_2023_goalies.csv',index_col=[0]) | |
summary_2023['pos'] = 'G' | |
summary_2022 = pd.read_csv('Drive/summary_2022_goalies.csv',index_col=[0]) | |
#team_games = pd.read_csv('Drive/team_games.csv') | |
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') | |
# cap_friendly_df = pd.read_csv('cap_friendly.csv') | |
# cap_friendly_df = cap_friendly_df[cap_friendly_df.POS == "G"] | |
# cap_friendly_df['POS_new'] = 'G' | |
# cap_friendly_df['new_length'] = cap_friendly_df['EXP. YEAR'] - 2022 | |
# cap_friendly_df['new_cap'] = cap_friendly_df['CAP HIT'].astype(str).str[1:] | |
# cap_friendly_df['new_cap'] = cap_friendly_df['new_cap'].str.replace(',','').astype(int)/1000000 | |
# cap_friendly_df['TEAM'] = cap_friendly_df[['TEAM']].replace(['LAK','NJD','SJS','TBL'],['L.A','N.J','S.J','T.B']) | |
# cap_friendly_df['new_cap'] = round(cap_friendly_df['new_cap'],1) | |
# cap_friendly_df['player_no_acc'] = cap_friendly_df['PLAYER'].str.normalize('NFKD').str.encode('ascii', errors='ignore').str.decode('utf-8') | |
# # bios_pd['player_no_acc'] = bios_pd['player'].str.normalize('NFKD').str.encode('ascii', errors='ignore').str.decode('utf-8') | |
# cap_friendly_df['sheets'] = "$"+cap_friendly_df['new_cap'].astype(str)+ "M x "+cap_friendly_df['new_length'].astype(str) | |
# #cap_friendly_df = cap_friendly_df.merge(right=summary_2023_all[['player_no_acc','player_id']],how='left',left_on=['player_no_acc'],right_on=['player_no_acc']).fillna("") | |
# #cap_friendly_df.to_csv('cap_friendly.csv') | |
# import difflib | |
# summary_2023['yahoo_name'] = summary_2023.Player.map(lambda x: (difflib.get_close_matches(x, df_2023.full)[:1] or [None])[0]) | |
# summary_2023['cap_name'] = summary_2023['Player'].apply(lambda x: (difflib.get_close_matches(x, cap_friendly_df['player_no_acc'])[:1] or [None])[0]) | |
yahoo_to_nhl_df = pd.read_csv('yahoo_to_nhl.csv', encoding='unicode_escape') | |
print('made it here') | |
#summary_2023 = summary_2023.merge(right=cap_friendly_df[['player_no_acc','POS_new','sheets','AGE']],left_on=['cap_name','pos'],right_on=['player_no_acc','POS_new'],how='left') | |
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=df_2023[['full','pos_new','percent_owned','display_position']],left_on=['cap_name','pos'],right_on=['full','pos_new'],how='left').fillna('') | |
game_log_all_on_ice = pd.read_csv('player_games_goalies.csv',index_col=[0]) | |
summary_all_on_ice_2023 = pd.read_csv('summary_2023_goalies.csv',index_col=[0]) | |
summary_all_on_ice_2022 = pd.read_csv('Drive/summary_2022_goalies.csv',index_col=[0]) | |
skater_dict = game_log_all_on_ice.sort_values(by='date',ascending=False).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['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 Goalie",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 = "900px",width="1200px") | |
) | |
), | |
) | |
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): | |
def plot(): | |
def show_values(axs, orient="v", space=-1,stat = [],rank_n=[],linewidth=2,fontsize=10): | |
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()) | |
value_stat = '{:.2f}'.format(float(stat[i])) | |
rank = rank_n[i] | |
ax.text(_x, -4.2, value_stat, ha="center",fontstyle='italic',fontsize=10) | |
ax.text(_x, -4.7, rank, ha="center",fontstyle='italic',fontsize=10) | |
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",fontsize=10) | |
if isinstance(axs, np.ndarray): | |
for idx, ax in np.ndenumerate(axs): | |
_single(ax) | |
else: | |
_single(axs) | |
# from matplotlib import rc, font_manager | |
# rc('text', usetex=True) | |
# rc('font',**{'family':'sans-serif','sans-serif':['Century Gothic']}) | |
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()) | |
print('made it here') | |
last_games = input.last_game_id() | |
name = summary_2023.loc[summary_2023.player_id == player_id].Player.values[0] | |
#last_games = int(input.last_game_id()) | |
today = str(datetime.now().date()) | |
game_log_all_on_ice_small = game_log_all_on_ice[game_log_all_on_ice.player_id==player_id].reset_index(drop=True) | |
summary_all_on_ice_2023_small = summary_all_on_ice_2023[summary_all_on_ice_2023.player_id==player_id].reset_index(drop=True) | |
summary_all_on_ice_2022_small = summary_all_on_ice_2022[summary_all_on_ice_2022.player_id==player_id].reset_index(drop=True) | |
df_last_games = pd.DataFrame(data={'Games':[last_games]}) | |
df_last_games['TOI'] = game_log_all_on_ice_small['TOI'][:last_games].sum() | |
df_last_games['TOI/G'] = game_log_all_on_ice_small['TOI'][:last_games].sum()/df_last_games.Games | |
df_last_games['PK TOI/G'] = game_log_all_on_ice_small['TOI_pk'][:last_games].sum()/df_last_games.Games | |
df_last_games['All SV%'] = 1 - game_log_all_on_ice_small['Goals Against'][:last_games].sum()/game_log_all_on_ice_small['Shots Against'][:last_games].sum() | |
df_last_games['5v5 SV%'] = 1 - game_log_all_on_ice_small['Goals Against_5v5'][:last_games].sum()/game_log_all_on_ice_small['Shots Against_5v5'][:last_games].sum() | |
df_last_games['PK SV%'] = 1 - game_log_all_on_ice_small['Goals Against_pk'][:last_games].sum()/game_log_all_on_ice_small['Shots Against_pk'][:last_games].sum() | |
df_last_games['LDSV%'] = 1 - game_log_all_on_ice_small['LD Goals Against'][:last_games].sum()/game_log_all_on_ice_small['LD Shots Against'][:last_games].sum() | |
df_last_games['MDSV%'] = 1 - game_log_all_on_ice_small['MD Goals Against'][:last_games].sum()/game_log_all_on_ice_small['MD Shots Against'][:last_games].sum() | |
df_last_games['HDSV%'] = 1 - game_log_all_on_ice_small['HD Goals Against'][:last_games].sum()/game_log_all_on_ice_small['HD Shots Against'][:last_games].sum() | |
df_last_games['GSAx/60'] = (game_log_all_on_ice_small['xG Against'][:last_games].sum() - game_log_all_on_ice_small['Goals Against'][:last_games].sum())/df_last_games.TOI*60 | |
df_last_games['xGA/60'] = (game_log_all_on_ice_small['xG Against'][:last_games].sum() )/df_last_games.TOI*60 | |
df_last_games['GA/60'] = (game_log_all_on_ice_small['Goals Against'][:last_games].sum())/df_last_games.TOI*60 | |
df_season = pd.DataFrame(data={'Games':[summary_all_on_ice_2023_small.GP[0]]}) | |
df_season['TOI'] = summary_all_on_ice_2023_small['TOI'].sum() | |
df_season['TOI/G'] = summary_all_on_ice_2023_small['TOI'].sum()/df_season.Games | |
df_season['PK TOI/G'] = summary_all_on_ice_2023_small['TOI_pk'].sum()/df_season.Games | |
df_season['All SV%'] = 1 - summary_all_on_ice_2023_small['GA'].sum()/summary_all_on_ice_2023_small['SA'].sum() | |
df_season['5v5 SV%'] = 1 - summary_all_on_ice_2023_small['GA_5v5'].sum()/summary_all_on_ice_2023_small['SA_5v5'].sum() | |
df_season['PK SV%'] = 1 - summary_all_on_ice_2023_small['GA_pk'].sum()/summary_all_on_ice_2023_small['SA_pk'].sum() | |
df_season['LDSV%'] = 1 - summary_all_on_ice_2023_small['LDGA'].sum()/summary_all_on_ice_2023_small['LDSA'].sum() | |
df_season['MDSV%'] = 1 - summary_all_on_ice_2023_small['MDGA'].sum()/summary_all_on_ice_2023_small['MDSA'].sum() | |
df_season['HDSV%'] = 1 - summary_all_on_ice_2023_small['HDGA'].sum()/summary_all_on_ice_2023_small['HDSA'].sum() | |
df_season['GSAx/60'] = (summary_all_on_ice_2023_small['xGA'].sum() - summary_all_on_ice_2023_small['GA'].sum())/summary_all_on_ice_2023_small['TOI'].sum()*60 | |
df_season['xGA/60'] = (summary_all_on_ice_2023_small['xGA'].sum())/summary_all_on_ice_2023_small['TOI'].sum()*60 | |
df_season['GA/60'] = (summary_all_on_ice_2023_small['GA'].sum())/summary_all_on_ice_2023_small['TOI'].sum()*60 | |
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) | |
df_career_total = pd.DataFrame(data={'Games':[summary_all_on_ice_2022_small.GP[0]]}) | |
df_career_total['TOI'] = summary_all_on_ice_2022_small['TOI'].sum() | |
df_career_total['TOI/G'] = summary_all_on_ice_2022_small['TOI'].sum()/df_career_total.Games | |
df_career_total['PK TOI/G'] = summary_all_on_ice_2022_small['TOI_pk'].sum()/df_career_total.Games | |
df_career_total['All SV%'] = 1 - summary_all_on_ice_2022_small['GA'].sum()/summary_all_on_ice_2022_small['SA'].sum() | |
df_career_total['5v5 SV%'] = 1 - summary_all_on_ice_2022_small['GA_5v5'].sum()/summary_all_on_ice_2022_small['SA_5v5'].sum() | |
df_career_total['PK SV%'] = 1 - summary_all_on_ice_2022_small['GA_pk'].sum()/summary_all_on_ice_2022_small['SA_pk'].sum() | |
df_career_total['LDSV%'] = 1 - summary_all_on_ice_2022_small['LDGA'].sum()/summary_all_on_ice_2022_small['LDSA'].sum() | |
df_career_total['MDSV%'] = 1 - summary_all_on_ice_2022_small['MDGA'].sum()/summary_all_on_ice_2022_small['MDSA'].sum() | |
df_career_total['HDSV%'] = 1 - summary_all_on_ice_2022_small['HDGA'].sum()/summary_all_on_ice_2022_small['HDSA'].sum() | |
df_career_total['GSAx/60'] = (summary_all_on_ice_2022_small['xGA'].sum() - summary_all_on_ice_2022_small['GA'].sum())/summary_all_on_ice_2022_small['TOI'].sum()*60 | |
df_career_total['xGA/60'] = (summary_all_on_ice_2022_small['xGA'].sum())/summary_all_on_ice_2022_small['TOI'].sum()*60 | |
df_career_total['GA/60'] = (summary_all_on_ice_2022_small['xGA'].sum())/summary_all_on_ice_2022_small['TOI'].sum()*60 | |
df_career_total.rename(index={0:'2022-23 ('+str(df_career_total.Games[0])+'GP)'},inplace=True) | |
df_career_total.rename(index={0:'2022-23 ('+str(df_career_total.Games[0])+'GP)'},inplace=True) | |
df_combined = df_last_games.append([df_season,df_career_total]) | |
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.fillna(0) | |
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 | |
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: | |
if 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(colormap(norm(-df_combined_t.values[[10],[0]] / df_combined_t.values[[10],[1]]))) | |
if df_combined_t.values[[10],[1]] < 0: | |
if 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(colormap(norm(-df_combined_t.values[[10],[0]] / df_combined_t.values[[10],[1]]))) | |
#age = summary_2023[summary_2023.player_id==player_id].reset_index(drop=True)['AGE'][0] | |
percent_owned = summary_2023[summary_2023.player_id==player_id].reset_index(drop=True).fillna(0)['percent_owned'][0] | |
yahoo_position = summary_2023[summary_2023.player_id==player_id].reset_index(drop=True).fillna('G')['display_position'][0] | |
# logging.getLogger('matplotlib.font_manager').disabled = True | |
nhl_logos = pd.read_csv("NHL Logos - NHL Logos.csv") | |
# image = image = "https://cms.nhl.bamgrid.com/images/headshots/current/168x168/"+str(player_id)+".png" | |
# logo = nhl_logos[nhl_logos.Team==game_log_all_on_ice_small.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.08,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=18,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.91,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=game_log_all_on_ice_small['Team'].reset_index(drop=True)[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(age),horizontalalignment='left',fontsize=22,fontname='Century Gothic') | |
# #fig.text(x=0.25,y=0.91,s=cap_friendly_df.loc[cap_friendly_df['player_no_acc']==name].reset_index()['sheets'][0],horizontalalignment='left',fontsize=22,fontname='Century Gothic') | |
# fig.text(x=0.25,y=0.91,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 = summary_2023.copy() | |
#test.loc[name == test.Player].reset_index().TOI[0]/1.5 | |
min_time = min(math.floor(test.loc[player_id == test.player_id].reset_index().TOI[0]/100)*100,test.GP.max()*30,math.ceil(test.loc[player_id == test.player_id].reset_index().TOI[0]/200)*100) | |
# min_time = min(math.floor(test.loc[name == test.Player].reset_index().TOI[0]/100)*100,test.GP.max()*10) | |
test_filter = test[(test.TOI >= min_time)]#.reset_index(drop=True) | |
test_filter['GSAx'] = test_filter['xGA'] - test_filter['GA'] | |
test_filter['GSAx/60'] = (test_filter['GSAx'])/(test_filter['TOI'])*60 | |
test_filter['GAA'] = (test_filter['GA'])/(test_filter['TOI'])*60 | |
test_filter['xG Against/60'] = (test_filter['xGA'])/(test_filter['TOI'])*60 | |
test_filter['SV% (All)'] = (test_filter['SV'])/(test_filter['SA']) | |
test_filter['SV% (5v5)'] = (test_filter['SV_5v5'])/(test_filter['SA_5v5']) | |
test_filter['SV% (PK)'] = (test_filter['SV_pk'])/(test_filter['SA_pk']) | |
test_filter['LDSV%'] = (test_filter['LDSV'])/(test_filter['LDSA']) | |
test_filter['MDSV%'] = (test_filter['MDSV'])/(test_filter['MDSA']) | |
test_filter['HDSV%'] = (test_filter['HDSV'])/(test_filter['HDSA']) | |
test_filter['GSAx/60 Z-Score'] = (test_filter['GSAx/60']-test_filter['GSAx/60'].mean())/test_filter['GSAx/60'].std() | |
test_filter['GA/60 Z-Score'] = -(test_filter['GAA']-test_filter['GAA'].mean())/test_filter['GAA'].std() | |
test_filter['xGA/60 Z-Score'] = -(test_filter['xG Against/60']-test_filter['xG Against/60'].mean())/test_filter['xG Against/60'].std() | |
test_filter['SV% (All) Z-Score'] = (test_filter['SV% (All)']-test_filter['SV% (All)'].mean())/test_filter['SV% (All)'].std() | |
test_filter['SV% (5v5) Z-Score'] = (test_filter['SV% (5v5)']-test_filter['SV% (5v5)'].mean())/test_filter['SV% (5v5)'].std() | |
test_filter['SV% (PK) Z-Score'] = (test_filter['SV% (PK)']-test_filter['SV% (PK)'].mean())/test_filter['SV% (PK)'].std() | |
test_filter['LDSV% Z-Score'] = (test_filter['LDSV%']-test_filter['LDSV%'].mean())/test_filter['LDSV%'].std() | |
test_filter['MDSV% Z-Score'] = (test_filter['MDSV%']-test_filter['MDSV%'].mean())/test_filter['MDSV%'].std() | |
test_filter['HDSV% Z-Score'] = (test_filter['HDSV%']-test_filter['HDSV%'].mean())/test_filter['HDSV%'].std() | |
values_1 = test_filter.loc[name == test_filter.Player][['GSAx/60','GAA','xG Against/60']].reset_index(drop=True).loc[0] | |
values_2 = test_filter.loc[name == test_filter.Player][['SV% (All)','SV% (5v5)','SV% (PK)']].reset_index(drop=True).loc[0] | |
values_3 = test_filter.loc[name == test_filter.Player][['LDSV%','MDSV%','HDSV%']].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[name == test_filter.Player][test_filter.columns[-9:]].values.flatten().tolist(),2)) | |
#player = [*player, player[0]] | |
label_loc = np.linspace(start=0, stop=2 * np.pi, num=len(player)) | |
# 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 = [i[:-8] for i in test_filter.columns[-9:]] | |
#categories[0] = 'GSAx/60' | |
player = list(np.around(test_filter.loc[name == test_filter.Player][test_filter.columns[-9:]].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') | |
rank_1 = list(test_filter[values_1.index].rank(method='min',ascending=False).loc[name == test_filter.Player].reset_index(drop=True).astype(int).iloc[0][[categories[0]]]) | |
rank_1 = rank_1 + list(test_filter[values_1.index].rank(method='min',ascending=True).loc[name == test_filter.Player].reset_index(drop=True).astype(int).iloc[0][['GAA','xG Against/60']]) | |
rank_2 = list(test_filter[values_2.index].rank(method='min',ascending=False).loc[name == test_filter.Player].reset_index(drop=True).astype(int).iloc[0]) | |
rank_3 = list(test_filter[values_3.index].rank(method='min',ascending=False).loc[name == test_filter.Player].reset_index(drop=True).astype(int).iloc[0]) | |
import scipy as sp | |
import scipy.interpolate | |
game_log_all_on_ice_small['GSAx'] = game_log_all_on_ice_small['xG Against'] - game_log_all_on_ice_small['Goals Against'] | |
#game_log_all_on_ice_small['game'] = game_log_all_on_ice_small.groupby('player_id').cumcount() | |
game_log_all_on_ice_small = game_log_all_on_ice_small.sort_values(by=['game']) | |
new_length = game_log_all_on_ice_small.game.max()*100 | |
new_x = np.linspace(game_log_all_on_ice_small.game.min(), game_log_all_on_ice_small.game.max(), new_length) | |
new_y = sp.interpolate.interp1d(game_log_all_on_ice_small.game,game_log_all_on_ice_small['GSAx'].cumsum(),kind='linear')(new_x) | |
new_df = pd.DataFrame(columns=['Game','GSAx']) | |
new_df['Game'] = new_x | |
new_df['GSAx'] = new_y | |
# 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 | |
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: | |
if 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(colormap(norm(-df_combined_t.values[[10],[0]] / df_combined_t.values[[10],[1]]))) | |
if df_combined_t.values[[10],[1]] < 0: | |
if 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(colormap(norm(-df_combined_t.values[[10],[0]] / df_combined_t.values[[10],[1]]))) | |
sns.set_theme(style="whitegrid", palette="pastel") | |
fig = plt.figure(figsize=(12, 9),dpi=300) | |
fig.set_facecolor('white') | |
ax1 = plt.subplot(1,2,1) | |
ax2 = plt.subplot(3,2,2) | |
ax3 = plt.subplot(3,2,4) | |
ax4 = plt.subplot(3,2,6) | |
axes = [ax1, ax2, ax3, ax4] | |
# 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) | |
# ax[0][0].axis('off') | |
# ax[1][0].axis('off') | |
# ax[0][0].axis('off') | |
# ax[1][0].axis('off') | |
# image = "https://cms.nhl.bamgrid.com/images/headshots/current/168x168/"+str(player_id)+".png" | |
# logo = nhl_logos[nhl_logos.Team==game_log_all_on_ice_small.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) | |
# im = plt.imread(image) | |
# ax1 = fig.add_axes([0.25,0.76,0.12,0.12], anchor='NW', zorder=1) | |
# ax1.imshow(im) | |
# ax1.axis('off') | |
# imr = plt.imread(logo) | |
# ax1 = fig.add_axes([0.18,0.76,0.75,0.075], anchor='NW', zorder=1) | |
# ax1.imshow(imr) | |
# ax1.axis('off') | |
# image = "https://cms.nhl.bamgrid.com/images/headshots/current/168x168/"+str(player_id)+".png" | |
#f"https://assets.nhle.com/mugs/nhl/20232024/BUF/8482221.png" | |
#image = "https://cms.nhl.bamgrid.com/images/headshots/current/168x168/"+str(player_id)+".png" | |
# 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: | |
# print('Error') | |
#image = "https://cms.nhl.bamgrid.com/images/headshots/current/168x168/"+str(player_id)+".png" | |
logo = nhl_logos[nhl_logos.Team==game_log_all_on_ice_small.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() | |
# #im = plt.imread(image) | |
# im = OffsetImage(im, zoom=.50) | |
# ab = AnnotationBbox(im, (0.73, 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=.065) | |
ab = AnnotationBbox(imr, (0.5, 0.765), xycoords='axes fraction', box_alignment=(0.0,0.0),bboxprops={'edgecolor':'white'}) | |
ax1.add_artist(ab) | |
sub_value = 0.16 | |
ax1.text(x=0.5,y=1.13-sub_value,s='NHL Player Summary',horizontalalignment='center',fontsize=28, fontweight='bold',ha='center') | |
ax1.text(x=0.5,y=1.08-sub_value,s='2023-24 Season',horizontalalignment='center',fontsize=18,fontname='Century Gothic', fontstyle='italic',ha='center') | |
ax1.text(x=0.125,y=1.04-sub_value,s='Player',horizontalalignment='center',fontsize=14,fontname='Century Gothic', fontweight='bold') | |
ax1.text(x=0.125,y=1.005-sub_value,s='Team',horizontalalignment='center',fontsize=14,fontname='Century Gothic', fontweight='bold') | |
ax1.text(x=0.125,y=0.97-sub_value,s='Position',horizontalalignment='center',fontsize=14,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.125,y=0.935-sub_value,s='Roster%',horizontalalignment='center',fontsize=14,fontname='Century Gothic', fontweight='bold') | |
ax1.text(x=0.25,y=1.04-sub_value,s=name,horizontalalignment='left',fontsize=14,fontname='Century Gothic') | |
ax1.text(x=0.25,y=1.005-sub_value,s=list(game_log_all_on_ice_small['Team'].reset_index(drop=True))[0],horizontalalignment='left',fontsize=14,fontname='Century Gothic') | |
ax1.text(x=0.25,y=0.97-sub_value,s=yahoo_position,horizontalalignment='left',fontsize=14,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.25,y=0.935-sub_value,s=str(int(percent_owned*100))+'%',horizontalalignment='left',fontsize=14,fontname='Century Gothic') | |
ax1.text(x=0.55,y=0.07,s='Note: Last Games compares to 2023-24. 2023-24 compares to 2022-23.',horizontalalignment='center',fontsize=9,fontname='Century Gothic',va='bottom') | |
ax1.axis("off") | |
ax1.set_facecolor('white') | |
# [colormap(norm(0.8)),colormap(norm(1)),colormap(norm(1.2))] | |
#table_scale = ax1.table(cellText=['-20%','±0%','+20%'],cellLoc='center',rowLoc='center', bbox=[0.20, 0.1, 0.8, 0.05],cellColours=["#4285F4","white",'#FBBC04']) | |
table_scale = ax1.table(cellText=[['-20%','±0%','+20%']],rowLabels=[' Scale '], | |
cellLoc='center',rowLoc='center', bbox=[0.20, 0.03, 0.8, 0.03],cellColours=[[colormap(norm(0.8)),colormap(norm(1)),colormap(norm(1.2))]]) | |
table_scale.set_fontsize(10) | |
table_scale.scale(1, 0.5) | |
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: | |
print('1') | |
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: | |
print('2') | |
#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: | |
print('3') | |
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]]))) | |
table = ax1.table(cellText=df_combined_t.values, colLabels=df_combined_t.columns,rowLabels=df_combined_t.index | |
, cellLoc='center',rowLoc='center', bbox=[0.20, 0.1, 0.8, 0.65],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 < 4*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()))) | |
elif n_c < 10*3: | |
if cell.get_text().get_text() in format_col.astype(str).values: | |
cell.get_text().set_text('{:,.3f}'.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('{:,.2f}'.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 < 4*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()))) | |
elif n_c < 10*3: | |
if cell.get_text().get_text() in format_col.astype(str).values: | |
cell.get_text().set_text('{:,.3f}'.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('{:,.2f}'.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 < 4*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()))) | |
elif n_c < 10*3: | |
if cell.get_text().get_text() in format_col.astype(str).values: | |
cell.get_text().set_text('{:,.3f}'.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('{:,.2f}'.format(float(cell.get_text().get_text()))) | |
n_c = n_c + 1 | |
#ax1.text('') | |
#fig.tight_layout() | |
#categories[0:7] = ['G/GP','A/GP','P/GP','PPP/GP','S/GP','Hits/GP','Blk/GP'] | |
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] | |
sns.barplot(data=test_filter,x=categories[0:3],y=player[0:3],palette=color_scheme[0:3],edgecolor='black',ax=ax2) | |
ax2.set_title("Goals Against Rates Z-Score (min. "+str(min_time)+' 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,fontsize=10) | |
ax2.grid(axis = 'y',linestyle = '-', linewidth = 0.5,alpha=0.3) | |
ax2.tick_params(axis='x', which='major', labelsize=6) | |
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[3:9],y=player[3:9],palette=color_scheme[3:9],edgecolor='black',ax=ax3) | |
ax3.set_title("Save% Z-Score (min. "+str(min_time)+' 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') | |
ax2.set_ylabel('Z-Score', fontsize=15,fontname='Century Gothic') | |
def show_values(axs, orient="v", space=-1,stat = [],rank_n=[],fontsize=10): | |
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()) | |
value_stat = '{:.3f}'.format(float(stat[i])) | |
rank = rank_n[i] | |
ax.text(_x, -4.2, value_stat, ha="center",fontstyle='italic',fontsize=fontsize) | |
ax.text(_x, -4.7, rank, ha="center",fontstyle='italic',fontsize=fontsize) | |
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",fontsize=fontsize) | |
if isinstance(axs, np.ndarray): | |
for idx, ax in np.ndenumerate(axs): | |
_single(ax) | |
else: | |
_single(axs) | |
show_values(ax3,stat = pd.concat([values_2,values_3]),rank_n=rank_2+rank_3,fontsize=10) | |
# show_values(ax4,stat = values_3,rank_n=rank_3) | |
ax2.text(-0.5, -4.2, '2023-24', ha="right",fontstyle='italic',zorder=1,fontsize=10) | |
ax3.text(-0.5, -4.2, '2023-24', ha="right",fontstyle='italic',fontsize=10) | |
# ax4.text(-0.5, -4.2, '2022-23', ha="right",fontstyle='italic') | |
ax2.text(-0.5, -4.7, 'Rank (of '+str(len(test_filter))+")", ha="right",fontstyle='italic',fontsize=10) | |
ax3.text(-0.5, -4.7, 'Rank (of '+str(len(test_filter))+")", ha="right",fontstyle='italic',fontsize=10) | |
# ax4.text(-0.5, -4.7, 'Rank (of '+str(len(test_filter))+")", ha="right",fontstyle='italic') | |
# 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) | |
# sns.lineplot(x=game_log_all.Game,y=game_log_all.rolling(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(game_log_all.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([math.floor(min(game_log_all.TOI)/5)*5, math.ceil(max((game_log_all.rolling(last_games).mean().fillna(0)['TOI']))/5)*5]) | |
# 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=game_log_pp.Game,y=game_log_pp.rolling(last_games).sum()['PP_TOI']/game_log_pp.rolling(last_games).sum()['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=game_log_all.Game,y=game_log_all.rolling(last_games).mean()['Total Points'],ax=ax6,color='#FFB000',label='Points',linewidth = 2) | |
# sns.lineplot(x=game_log_pp.Game,y=game_log_pp.rolling(last_games).mean()['Total Points'],ax=ax6,color='#648FFF',label='PP Points',linewidth = 2) | |
# sns.lineplot(x=game_log_all.Game,y=game_log_all.rolling(last_games).mean()['Goals'],ax=ax6,color='#DC267F',label='Goals',linewidth = 2) | |
# sns.lineplot(x=game_log_all.Game,y=game_log_all.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(game_log_all.Game)]) | |
# ax6.set_ylim([0, round(max((game_log_all.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,fontname='Century Gothic') | |
# ax6.set(xlabel='Game', ylabel='Value Per Game') | |
positive_df = new_df.copy() | |
positive_df[positive_df.GSAx < 0] = np.NaN | |
negative_df = new_df.copy() | |
negative_df[negative_df.GSAx > 0] = np.NaN | |
# positive_df = positive_df.sort_values(by='Game') | |
# negative_df = negative_df.sort_values(by='Game') | |
#sns.lineplot(x=game_log_all_on_ice_small.Game,y=game_log_all_on_ice_small.rolling(last_games).mean()['GSAx'],ax=ax4,color='#FFB000',linewidth = 2,label='Rolling GSAx') | |
if not positive_df.dropna().empty and negative_df.dropna().empty: | |
sns.lineplot(x=positive_df.Game,y=positive_df.GSAx,ax=ax4,color='#FFB000',linewidth = 1,label='Cumulative GSAx',alpha=1,linestyle='-') | |
#threshold_plot(ax4, new_x,new_y, 0, '#648FFF', '#FFB000',linewidth=2) | |
elif positive_df.dropna().empty and not negative_df.dropna().empty: | |
sns.lineplot(x=negative_df.Game,y=negative_df.GSAx,ax=ax4,color='#648FFF',linewidth = 1,alpha=1,linestyle='-',label='Cumulative GSAx') | |
print('this') | |
else: | |
sns.lineplot(x=positive_df.Game,y=positive_df.GSAx,ax=ax4,color='#FFB000',linewidth = 1,label='Cumulative GSAx',alpha=1,linestyle='-') | |
sns.lineplot(x=negative_df.Game,y=negative_df.GSAx,ax=ax4,color='#648FFF',linewidth = 1,alpha=1,linestyle='-') | |
#ax4.legend(fontsize=10,ncol=5,loc='upper left') | |
ax4.xaxis.set_major_locator(MaxNLocator(integer=True)) | |
ax4.set_xlim([1, np.max(game_log_all_on_ice_small.game)]) | |
ax4.set_ylim([min(round(min((game_log_all_on_ice_small['GSAx'].cumsum()))*1)/1-1,-1), max(round(max((game_log_all_on_ice_small['GSAx'].cumsum()))*1)/1+2,3)]) | |
ax4.grid(axis = 'x',linestyle = '-', linewidth = 0.5,alpha=0.3) | |
ax4.grid(axis = 'y',linestyle = '-', linewidth = 0.5,alpha=0.3) | |
ax4.set_title("Cumulative Goals Saved Above Expected",fontsize=14,fontname='Century Gothic') | |
ax4.set(xlabel='Game', ylabel='GSAx') | |
ax4.yaxis.set_major_locator(MaxNLocator(integer=True)) | |
ax4.get_legend().remove() | |
fig.text(x=0.05,y=0.045,s='Created By: @TJStats',horizontalalignment='left',fontsize=10)#,fontname='Century Gothic') | |
fig.text(x=0.05,y=0.02,s='Data: Natural Stat Trick, CapFriendly, Yahoo Fantasy',horizontalalignment='left',fontsize=10)#,fontname='Century Gothic') | |
fig.text(x=0.5,y=0.02,s=str(date.today()),horizontalalignment='center',fontsize=8)#,fontname='Century Gothic') | |
# #ax1.set_zorder(2) | |
ax4.stackplot(new_df.Game[new_df.GSAx>=0],new_df.GSAx[new_df.GSAx>=0], alpha=0.2,color='#FFB000') | |
ax4.stackplot(new_df.Game[new_df.GSAx<0],new_df.GSAx[new_df.GSAx<0], alpha=0.2,color='#648FFF') | |
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=1,xmax=max(game_log_all_on_ice_small['game']),color='black',linewidth=0.75) | |
#ax4.stackplot(game_log_all_on_ice_small["Game"], game_log_all_on_ice_small['GSAx'].cumsum(), color=['r' if v < 0 else '#FFB000' for v in game_log_all_on_ice_small['GSAx']],alpha=0.3) | |
ax2.tick_params(axis='both', which='major', labelsize=10,bottom=False,top=False) | |
ax3.tick_params(axis='both', which='major', labelsize=10,bottom=False,top=False) | |
ax4.tick_params(axis='both', which='major', labelsize=10,bottom=False,top=False) | |
# im_rain = plt.imread('https://upload.wikimedia.org/wikipedia/commons/thumb/3/31/Rainbow-gradient-fully-saturated.svg/1024px-Rainbow-gradient-fully-saturated.svg.png') | |
# ax1 = fig.add_axes([0,0,1,1], anchor='C') | |
# ax1.imshow(im_rain,alpha=0.3) | |
# ax1.set_aspect('auto') | |
# ax1.axis('off') | |
for key, cell in table.get_celld().items(): | |
cell.set_linewidth(0) | |
for key, cell in table_scale.get_celld().items(): | |
cell.set_linewidth(0) | |
ax2.set_xlim([-0.5, 2.5]) | |
ax3.set_xlim([-0.5, 5.5]) | |
plt.tight_layout(pad=0.3, w_pad=1, h_pad=0.5) | |
# if not os.path.exists('player_cards/goalies/'+name): | |
# os.makedirs('player_cards/goalies/'+name) | |
# # dir = 'players/' | |
# # for f in os.listdir(dir): | |
# # os.remove(os.path.join(dir, f)) | |
# plt.savefig('player_cards/goalies/'+name+'/'+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) |