I'm beginning on Python I want to add patches to a facet-grid with the following code and I get AttributeError: 'FacetGrid' object has no attribute 'add_patch'. I've done some extensive research but can't find any solution to this issue.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.patches import Circle, Rectangle, Arc
sns.set_style("white")
sns.set_color_codes()
def draw_pitch(ax=None, color='black', lw=2, outer_lines=True):
# If an axes object isn't provided to plot onto, just get current one
if ax is None:
ax = plt.gca()
I think there might be an issue with this plt.gca() but don't know how or if I should replace it?
# Create goal
goal = Rectangle((-15,0), 30, .5, linewidth=3, color=color)
# The box
box = Rectangle((-81, 0), 162, 66, linewidth=lw, color=color,
fill=False)
#6ybox
ybox = Rectangle((-37, 0), 74, 22, linewidth=lw, color=color, fill=False)
#Penaltyarc
Parc = Arc((0,44),73.4,73.4, theta1=37, theta2=143,linewidth=lw, color=color, fill=False)
#Penalty
PSpot = Circle((0,44),radius=.5, linewidth=lw, color=color, fill=False)
# List of the court elements to be plotted onto the axes
pitch_elements = [goal, box, ybox, PSpot,Parc]
if outer_lines:
# Draw the half court line, baseline and side out bound lines
outer_lines = Rectangle((-136, 0), 272, 210, linewidth=lw,
color=color, fill=False)
pitch_elements.append(outer_lines)
# Add the court elements onto the axes
for element in pitch_elements:
ax.add_patch(element)
return ax
plt.figure(figsize=(12,11))
draw_pitch(outer_lines=True)
plt.xlim(-136,136)
plt.ylim(0,210)
cmap = 'jet'
file = 'Chances23clean.csv'
df = pd.read_csv(file)
df.teamf=df.teamf.apply(str)
g = sns.FacetGrid(df, col="teamf", col_wrap=4,size=3.5,ylim=(210,0),xlim=(136,-136))
g = (g.map(sns.kdeplot,"primaryLocation_x", "primaryLocation_y", shade=True,cmap=cmap,n_levels=40).set_titles("{col_name}",fontsize=300).set_axis_labels("","").set_ylabels('').set_xticklabels('','').set_yticklabels(''))
draw_pitch(g)
OK so I've made some nice progress by doing the following. Instead of having on the above code :
draw_pitch(g)
I have replaced it by
draw_pitch(g.axes[0])
draw_pitch(g.axes[1])
draw_pitch(g.axes[2])
...
draw_pitch(g.axes[19])
And it works, but is there a way to simplify the code here? Thanks a lot.