Skip to content

Instantly share code, notes, and snippets.

@BlueSCar
Created January 23, 2021 20:21
Show Gist options
  • Save BlueSCar/65f868e8c6c0969b9dcaa57414f9a5ae to your computer and use it in GitHub Desktop.
Save BlueSCar/65f868e8c6c0969b9dcaa57414f9a5ae to your computer and use it in GitHub Desktop.
Plotting team logos in Python with matplotlib
import cfbd
import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
import pandas as pd
# Grab some stats from the CFBD API
stats = cfbd.StatsApi().get_advanced_team_season_stats(year=2020)
df = pd.DataFrame.from_records([dict(team=s.team, o_line_yards=s.offense.line_yards, d_line_yards=s.defense.line_yards) for s in stats])
# Need to grab team ids
teams = cfbd.TeamsApi().get_fbs_teams()
teams_df = pd.DataFrame.from_records([dict(id=t.id, school=t.school) for t in teams])
df = df.merge(teams_df, left_on='team', right_on='school')[['id', 'team', 'o_line_yards', 'd_line_yards']]
# This is the styling I use. Check out other themes here: https://matplotlib.org/3.2.1/gallery/style_sheets/style_sheets_reference.html
plt.style.use('fivethirtyeight')
# Graph sizing
plt.rcParams["figure.figsize"] = [20,10]
# You can download logos from here: https://drive.google.com/drive/folders/1BZ5bkR8K7ijzqDQkXjaBFthwsPx1JEpH?usp=sharing
# They come in two sizes. Extract them into the root of your script in a 'logos'. There should be no folders nested inside.
def getImage(path):
return OffsetImage(plt.imread("./logos/{0}.png".format(path)))
# Logo file names are <team_id>.png, so we just need ids to map teams to logos.
paths = df['id']
# Picking two random stats to plot
x = df['o_line_yards']
y = df['d_line_yards']
fig, ax = plt.subplots()
ax.scatter(x, y)
# Cycle through each point and add an image annotation
for x0, y0, path in zip(x, y,paths):
ab = AnnotationBbox(getImage(path), (x0, y0), frameon=False)
ax.add_artist(ab)
# Define labels and title
plt.title("Line Yards (2020)")
plt.xlabel('Line yards gained (avg)')
plt.ylabel('Line yards allowed (avg)')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment