Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Incorporate radar charts into the match and lastmatch embed #20

Open
PrettyHeatToast opened this issue Apr 19, 2020 · 1 comment
Open
Assignees
Labels
enhancement New feature or request

Comments

@PrettyHeatToast
Copy link
Collaborator

No description provided.

@PrettyHeatToast PrettyHeatToast added the enhancement New feature or request label Apr 19, 2020
@PrettyHeatToast
Copy link
Collaborator Author

PrettyHeatToast commented Apr 19, 2020

This code works as a seperate python file that generates a radar chart based on a match id and steam id.

import matplotlib.pyplot as plt
import numpy as np
import os
import json
import requests
import time


def average(list):
    return sum(list) / len(list)

def is_parsed(match):
    return match.get('version', None) is not None


def get_match(match_id):
    if os.path.isfile(f"resources/cached_matches/{match_id}.json"):
        with open(f"resources/cached_matches/{match_id}.json", 'r') as f:
            return json.load(f)
    else:
        matchdata = requests.get(
            f'https://api.opendota.com/api/matches/{match_id}').json()

        while matchdata == {'error': 'rate limit exceeded'}:
            print('The rate limit was passed')
            time.sleep(5)
            matchdata = (requests.get(
                f"https://api.opendota.com/api/matches/{match_id}")).json()
        if is_parsed(matchdata):
            with open(f"resources/cached_matches/{match_id}.json", 'w') as jsonFile:
                json.dump(matchdata, jsonFile)
        return matchdata

def add_to_radar(match_id):
    match = get_match(match_id)
    player = next(p for p in match['players'] if p['account_id'] == steamid)
    bm = player['benchmarks']
    values = [round(bm['tower_damage']['pct'] * 100, 2),
            round(bm['hero_damage_per_min']['pct'] * 100, 2),
            round(bm['kills_per_min']['pct'] * 100, 2),
            round(bm['last_hits_per_min']['pct'] * 100, 2),
            round(bm['lhten']['pct'] * 100, 2),
            round(bm['hero_healing_per_min']['pct'] * 100, 2),
            round(bm['stuns_per_min']['pct'] * 100, 2),
            round(bm['gold_per_min']['pct'] * 100, 2),
            round(bm['xp_per_min']['pct'] * 100, 2), ]
    values += values[:1]
    
    for key in rankings:
        rank_color = ""
        if rankings[key]['Demotion upon'] < average(values) < rankings[key]['Promotion upon']:
            rank_color = "#" + (hex(int(rankings[key]['color'])))[2:]
            break
    
    ax.plot(angles, values, color=rank_color, linewidth=1)
    ax.fill(angles, values, color=rank_color, alpha=0.25)


with open('resources/json_files/rankings.json', 'r') as f:
    rankings = json.load(f)

# Each attribute we'll plot in the radar chart
labels = ["Tower Damage", "Hero Damage", "Kills", "Last Hits",
          "Last Hits @ 10", "Hero Healing", "Stuns", "Gold", "Experience"]

# Number of variables we're plotting
num_vars = len(labels)

# Split the circle into even parts and save the angles so we know where to put each axis
angles = np.linspace(0, 2 * np.pi, num_vars, endpoint=False).tolist()

# The plot is a circle, so we need to "complete the loop" and append the start value to the end
angles += angles[:1]

# ax = plt.subplot(polar=True)
fig, ax = plt.subplots(figsize=(10, 10), subplot_kw=dict(polar=True))





# Input and adding the data to the chart
steamid = 189996985
match_id = 5364759182

add_to_radar(match_id)



# Fix axis to go in the right order and start at the top
ax.set_theta_offset(np.pi / 2)
ax.set_theta_direction(-1)

# Draw axis lines for each angle and label
ax.set_thetagrids(np.degrees(angles), labels)

# Go through labels and adjust alignment based on where it is in the circle
for label, angle in zip(ax.get_xticklabels(), angles):
    if angle in (0, np.pi):
        label.set_horizontalalignment('center')
    elif 0 < angle < np.pi:
        label.set_horizontalalignment('left')
    else:
        label.set_horizontalalignment('right')

# Ensure radar goes from 0 to 100.
ax.set_ylim(0, 100)

# Set position of y-labels (0-100) to be in the middle
# of the first two axes.
ax.set_rlabel_position(180 / num_vars)

# Add some styling
# Change the ticksize
ax.tick_params(axis='y', labelsize=16)
ax.tick_params(axis='x', labelsize=20)

# Change the color of the tick labels
ax.tick_params(colors='#AAAAAA')
# Change the color of the gridlines
ax.grid(color='#AAAAAA')
# Change the color of the outermost gridline
ax.spines['polar'].set_color('#AAAAAA')

plt.savefig("Radar chart Transparent", transparent=True)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants