<jupyter_start><jupyter_text>League Analysis ExampleA example of analysis in game data from riots api.This notebook was written to show examples of how to use the LeagueAnalysis class to get data from riot, and how to view the the data within the dataframes. Due to the size of this particular file, GitHub believes that this repo is primarally a jupyter notebook repo.  However, more efford has been placed into creating a class that cleans the data, retieves the data, and stores the data locally. I personally find that notebooks are a great way to display pd.DataFrames, and this is the prime reason why I have included this notebook.<jupyter_code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from LeagueAnalysis import LeagueAnalysis<jupyter_output><empty_output><jupyter_text>Firstly initalise the class with **your** working api key.You can obtain a api key from: https://developer.riotgames.com/. However, the api key is only valid for 24hours.  This is one of reasons for caching the reponses from riots api within a local databse.<jupyter_code># Initalise the class with your working api key:
apiKey = "RGAPI-be013ceb-17d3-445a-82fa-e1bd7bba68fk" # <- example key. 
lolA = LeagueAnalysis(apiKey, summoner_name="Moving Object 1")<jupyter_output><empty_output><jupyter_text>List of examples within this notebook- Example 1: Creating a mastery list- Example 2: Retrieving match id's.- Example 3: Event data.- Example 4: Champion timeline data.- Example 5: Plotting mulit-game champion timeline data.- Example 6: Combiing multiple summaries into a single dataframe for a single champion.- Example 7: Plotting positional data on summonmers rift.- Example 8: Plotting kills and death locations.- Example 9: Plotting positional data on a summonmers rift -- champion data.  Example 1: creating a mastery listThe create_mastery_table method uses information returned from champion-mastery-v4 and the data dragon to create the resulting dataframe.<jupyter_code># Creating a champion mastery list:
df =  lolA.create_mastery_table()
df.head(10)<jupyter_output><empty_output><jupyter_text>This method has the option to override/use another summoner name other than the one used in the initalisation, as can be seen below.<jupyter_code># Creating a champion mastery list with a different summoner name:
df =  lolA.create_mastery_table(summoner_name='Froggen')
df.head(10)<jupyter_output><empty_output><jupyter_text>Example 2: Retrieving match id's.The only way to analysis match data via riot's api is by knowing the match id.  Fortunately, riot provides us with a end point to retieve these match id for a given summoner puuid. All of this is wrappeds up in **get_list_of_matches** method.  This method will retrieve the last 20 match_id, and store them locally for later use.<jupyter_code># get the last 20 match id:
match_list = lolA.get_list_of_matches()
print(match_list)<jupyter_output>['EUW1_5629430948', 'EUW1_5628510042', 'EUW1_5628428948', 'EUW1_5628289118', 'EUW1_5628285767', 'EUW1_5628278757', 'EUW1_5628130397', 'EUW1_5628124549', 'EUW1_5628110997', 'EUW1_5627993313', 'EUW1_5627768740', 'EUW1_5627764895', 'EUW1_5627742743', 'EUW1_5627731126', 'EUW1_5626969313', 'EUW1_5626875306', 'EUW1_5626891502', 'EUW1_5626707513', 'EUW1_5626662319', 'EUW1_5626447624']<jupyter_text>Due to locally caching these id's the method **get_list_of_stored_match_ids_for_summoner_name** will retieve the values saved locally.<jupyter_code>match_list = lolA.get_list_of_stored_match_ids_for_summoner_name("Moving Object 1")
print(match_list)<jupyter_output>['EUW1_5629430948', 'EUW1_5628510042', 'EUW1_5628428948', 'EUW1_5628289118', 'EUW1_5628285767', 'EUW1_5628278757', 'EUW1_5628130397', 'EUW1_5628124549', 'EUW1_5628110997', 'EUW1_5627993313', 'EUW1_5627768740', 'EUW1_5627764895', 'EUW1_5627742743', 'EUW1_5627731126', 'EUW1_5626969313', 'EUW1_5626875306', 'EUW1_5626891502', 'EUW1_5626707513', 'EUW1_5626662319', 'EUW1_5626447624']<jupyter_text>Example 3: Event data.Through the use of the match-v5 endpoint a timeline of events can obtained via the create_event_timeline_dataframe method using the match id we have obtained previously.<jupyter_code># create a event timeline dataframe for analysis
result = lolA.create_event_timeline_dataframe('EUW1_5612017679')
result.head()<jupyter_output><empty_output><jupyter_text>Dataframe manipulation can be implemented to filter down the dataframe for the events of interest.<jupyter_code># from the event timeline dataframe obtain only the kills and special kills (multi-kills?)
kill_df = result[
    (result['type'] == 'CHAMPION_KILL') |
    (result['type'] == 'CHAMPION_SPECIAL_KILL')
].copy()

kill_df['time'] = kill_df['timestamp']/1000/60

kill_df[
    [
        'time',
        'summonerName_victim',
        'championName_victim',
        'summonerName_killer',
        'championName_killer'
    ]
].sort_values('time').head()<jupyter_output><empty_output><jupyter_text>Example 4: Champion timeline data.Another set of statistics provided the match-v5 endpoint are time based stats of the summoner every minute of the game.  Such as total gold, and total damage dealt.  The create_champion_timeline_dataframe method will create a dataframe for all of these statistics.  However, some KPIs are nested within a dictionary and these can be extracted later if required.<jupyter_code># Create the chamption timeline dataframe -- this is mainly stats and kpi's
tl_data = lolA.create_champion_timeline_dataframe('EUW1_5612017679')<jupyter_output><empty_output><jupyter_text>The data within the champion timeline dataframe can be used to plot selected KPIs againts another chamption.  The cell below how to compare one summoner to another within a *single* game.<jupyter_code># Use the chamption timeline dataframe to plot the data

# Expant the damage stats and champion stats if required
champion_df_dict = lolA.parse_champion_timeline_dataframe(tl_data)

# Option 1: Plot everyones total gold:
champs_to_plot = tl_data['championName'].unique()

# Option 2: Explicitly select the champs:
champs_to_plot = ['Twitch','Xayah']

# Option 3: Select a roll
print('List of roles avaliable: ',tl_data['individualPosition'].unique())
champs_to_plot = tl_data[
    tl_data['individualPosition'] == 'BOTTOM' 
]['championName'].unique()

# Option 4: Your own way of deciding how to plot data

# Plotting the data
plotting_key = 'totalGold'
for champ in champs_to_plot:
    plt.plot(champion_df_dict[champ]['time'],champion_df_dict[champ][plotting_key])
    plt.grid(True)
    plt.xlabel('Minutes into game')
    plt.ylabel(plotting_key)
    
plt.legend(champs_to_plot)<jupyter_output>List of roles avaliable:  ['TOP' 'JUNGLE' 'MIDDLE' 'BOTTOM' 'UTILITY']<jupyter_text>Some of the KPIs which are nested maybe of intrest, such as true damage dealt. Implementing the expand_champion_stats method will expand these KPIs for the entire dataframe.<jupyter_code>%%time
# expand the DataFrame for additional KPI's/Stats
tl_data_expanded = lolA.expand_champion_stats(tl_data)<jupyter_output>Wall time: 5.26 s<jupyter_text>Similar to the plot above, the cell below plots the true damage dealt for the bot lane champions.<jupyter_code># parse out the information for each champ for easier plotting.
champion_df_dict = lolA.parse_champion_timeline_dataframe(tl_data_expanded)

# Or select a roll
print('List of roles avaliable: ',tl_data_expanded['individualPosition'].unique())
selected_role = 'BOTTOM'

champs_to_plot = tl_data_expanded[ tl_data['individualPosition'] == selected_role ]\
                ['championName'].unique()

df_key = 'trueDamageDone'
for champ in champs_to_plot:
    plt.plot(champion_df_dict[champ]['time'],champion_df_dict[champ][df_key])
    plt.grid(True)
    plt.xlabel('Minutes into game')
    plt.ylabel(df_key)
    
plt.legend(champs_to_plot)<jupyter_output>List of roles avaliable:  ['TOP' 'JUNGLE' 'MIDDLE' 'BOTTOM' 'UTILITY']<jupyter_text>Example 5 Plotting mulit-game champion timeline data.Interestingly, by downloading several match timeline's and match summaries it is possible to compare statistics from multiple games.  The example below demonstrates how to plot the total gold for several games for a single summoner name.<jupyter_code># Comparing stats from game-to-game opposing to champ-to-champ in a single game.

# Get the last 20 match id's:
list_of_games = lolA.get_list_of_matches()

# filter list if necessary, for example the last five games in the list_of_games
games_to_compare = list_of_games[-5:]

# set up data for plotting
game_data = {}
multi_df_dict = {}
for game in games_to_compare:
    game_data[game] = lolA.create_champion_timeline_dataframe(game)
    multi_df_dict[game] = lolA.parse_champion_timeline_dataframe(game_data[game], parse_on='summonerName')
        
df_key = 'totalGold'
summoner_name = lolA.summoner_name

for game in multi_df_dict:
    plt.plot(multi_df_dict[game][summoner_name]['time'],multi_df_dict[game][summoner_name][df_key])
    plt.grid(True)
    plt.xlabel('Minutes into game')
    plt.ylabel(df_key)
    plt.legend(games_to_compare)<jupyter_output><empty_output><jupyter_text>Similarly, the plot below shows the total number of minions kills over 5 different matches.<jupyter_code>df_key = 'minionsKilled'
summoner_name = lolA.summoner_name

for game in game_data:
    plt.plot(multi_df_dict[game][summoner_name]['time'],multi_df_dict[game][summoner_name][df_key])
    plt.grid(True)
    plt.xlabel('Minutes into game')
    plt.ylabel(df_key)
    plt.legend(games_to_compare)<jupyter_output><empty_output><jupyter_text>Example 6: Combiing multiple summaries into a single dataframe for a single champion.Another option is to group all the match details together in a single dataframe<jupyter_code>summary_df = lolA.combine_match_summaries('Moving Object 1',games_to_compare)
summary_df<jupyter_output><empty_output><jupyter_text>Example 7: Plotting positional data on summonmers rift.The method **plot_positional_data** is able to plot positional data when a column named positions" is passed.   The example blow uses the event data to plot all event for each team. Additionally, **plot_positional_data** is able to plot positional data for two seperate DataFrames.  The first DataFrame is asssumed that data is from teamId=100 (blue team), and the second DataFrame is data from teamId=200 (red team).<jupyter_code>example_plotting_data = lolA.create_event_timeline_dataframe('EUW1_5612017679')
example_plotting_dict = lolA.parse_champion_timeline_dataframe(example_plotting_data, parse_on='teamId')

lolA.plot_positional_data(example_plotting_dict[100.0],example_plotting_dict[200.0])<jupyter_output><empty_output><jupyter_text>Additionally, **plot_positional_data** has the option to number the event by DataFrame index.  Events also capture when champions destroyed turret plating, and it should be noted that these events can stack in the same location.<jupyter_code>tower_kills_team_1 =  example_plotting_dict[100.0][
    (example_plotting_dict[100.0]['type'] == 'BUILDING_KILL') 
][['time','type','position','summonerName_killer']].sort_values(by='time')

tower_kills_team_2 =  example_plotting_dict[200.0][
    (example_plotting_dict[200.0]['type'] == 'BUILDING_KILL') 
][['time','type','position','summonerName_killer']].sort_values(by='time')

lolA.plot_positional_data(tower_kills_team_1,
                          tower_kills_team_2,
                          index_label=True)<jupyter_output><empty_output><jupyter_text>Example 8: Plotting kills and death locations.<jupyter_code>example_plotting_data = lolA.create_event_timeline_dataframe('EUW1_5612017679')
example_plotting_data.columns
killing_data = lolA.parse_champion_timeline_dataframe(example_plotting_data, parse_on='summonerName_killer')
death_data = lolA.parse_champion_timeline_dataframe(example_plotting_data, parse_on='summonerName_victim')
lolA.plot_positional_data(death_data['Moving Object 2'],
                          killing_data['Moving Object 2'],
                          )
# kills -> blue, deaths-> read<jupyter_output><empty_output><jupyter_text>Example 8: Plotting positional data on a summonmers rift -- champion data.Champion based data contains a considerable more data than event data.  This will need to be filted to have any meaning.<jupyter_code>example_plotting_data = lolA.create_champion_timeline_dataframe('EUW1_5612017679')
example_plotting_dict = lolA.parse_champion_timeline_dataframe(example_plotting_data, parse_on='teamId')

lolA.plot_positional_data(example_plotting_dict[100.0],example_plotting_dict[200.0])
# positional data for a single champion

example_plotting_data = lolA.create_champion_timeline_dataframe('EUW1_5612017679')
example_plotting_data = lolA.expand_champion_stats(example_plotting_data)
example_plotting_data.columns

example_plotting_dict = lolA.parse_champion_timeline_dataframe(
    example_plotting_data, 
    parse_on='summonerName')

lolA.plot_positional_data(example_plotting_dict['Moving Object 2'])<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.08521765882171974, 'fraction_numerical': 0.047454237809567756, 'mean_word_length': 6.358800226372383, 'pattern_counts': {'":': 0, '<': 73, '<?xml version=': 0, '>': 74, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '19', 'dir': 'jupyter-structured-clean-dedup', 'id': '453438', 'license': 'MIT', 'n_tokens_mistral': 4727, 'n_tokens_neox': 4250, 'n_words': 1170, 'path': 'LeagueAnalysis/example notebook.ipynb', 'repo_name': 'cbostock/LeagueAnalysis', 'size': '13002'}