我从Python开始我想用以下代码添加补丁到facet-grid我得到 AttributeError:' FacetGrid'对象没有属性' add_patch'。我做了一些广泛的研究,但无法找到解决这个问题的方法。
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()
我认为这个plt.gca()可能存在问题,但我不知道应该如何替换它?
# 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)
好的,所以我通过以下方式取得了一些不错的进展。而不是上面的代码:
draw_pitch(g)
我已将其替换为
draw_pitch(g.axes[0])
draw_pitch(g.axes[1])
draw_pitch(g.axes[2])
...
draw_pitch(g.axes[19])
它有效,但有没有办法在这里简化代码?非常感谢。
答案 0 :(得分:0)
尝试将draw_pitch(g)
替换为draw_pitch(g.axes[0, 0])
。 Facetgrid将轴存储在2d numpy数组中,但如果facetgrid只有一个轴,则必须编写g.ax
。