Skip to content

Instantly share code, notes, and snippets.

Created January 23, 2021 20:21
What would you like to do?
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(, 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(, 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:'fivethirtyeight')
# Graph sizing
plt.rcParams["figure.figsize"] = [20,10]
# You can download logos from here:
# 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)
# 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