Skip to content

Instantly share code, notes, and snippets.

@MemphisMeng
Created January 3, 2021 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MemphisMeng/3f9a751344f54e4cd848ef573eaed8c1 to your computer and use it in GitHub Desktop.
Save MemphisMeng/3f9a751344f54e4cd848ef573eaed8c1 to your computer and use it in GitHub Desktop.
def barit(week, measure):
"""
Filters and plot the dataframe as a bar plot of teams' defence performance
Args:
-----
* week (str): the period to filter on, or "Overall" to display the entire season
* measure (str): the option of measurement
Returns:
--------
A matplotlib bar plot
"""
plot = df.copy()
if week != 'Overall':
week_num = int(week.split(' ')[1])
plot = plot[plot.week == week_num]
if measure == 'playResult':
defence = plot.groupby('defensiveTeam').agg({'playResult': 'mean'})
defence.rename(columns = {'playResult': 'mean'}, inplace=True)
elif measure == 'offensePlayResult':
defence = plot.groupby('defensiveTeam').agg({'offensePlayResult': 'mean'})
defence.rename(columns = {'offensePlayResult': 'mean'}, inplace=True)
elif measure == 'epa':
defence = plot.groupby('defensiveTeam').agg({'epa': 'mean'})
defence.rename(columns = {'epa': 'mean'}, inplace=True)
# Plot it (only if there's data to plot)
if len(plot) > 0:
fig, ax = plt.subplots(figsize=(15, 15))
ax.barh([i+1 for i in range(defence.shape[0])], defence['mean'].tolist())
ax.set_xlabel('Opponent\'s Average Gain', size=15)
ax.set_yticklabels([])
ax.set_title('Team Defence Performance', size=15)
for x0, y0, path in zip([i+1 for i in range(defence.shape[0])], defence['mean'].tolist(),
['../input/nfl-team-logos/' + file for file in sorted(os.listdir('../input/nfl-team-logos'))]):
ab = AnnotationBbox(getImage(path), (y0, x0), xybox=(-25, 0), frameon=False,
xycoords='data', boxcoords="offset points", pad=0)
ax.add_artist(ab)
else:
print("No data to show for current selection")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment