0

我开始使用 Python 我想使用以下代码向 facet-grid 添加补丁,我得到 AttributeError: 'FacetGrid' object has no attribute '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])

它可以工作,但是有没有办法在这里简化代码?非常感谢。

4

1 回答 1

0

尝试替换draw_pitch(g)draw_pitch(g.axes[0, 0]). Facetgrid 将轴存储在 2d numpy 数组中,但如果 facetgrid 只有一个轴,则必须编写g.ax.

于 2017-02-21T07:43:31.647 回答