Spaces:
Running
Running
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/453.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): | |
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) |