首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么我不能画这个?(Python-足球场)

为什么我不能画这个?(Python-足球场)
EN

Stack Overflow用户
提问于 2021-02-18 20:57:34
回答 1查看 104关注 0票数 0

我目前正试图在足球场上规划所有在比赛中传递的传球,并为此编写了一些代码。我能够完美地画出每一个镜头(下面的代码),但现在我正试图绘制通行证,但它不起作用。你能帮我找出我的错误吗?谢谢

这是我目前陷入困境的代码。此代码绘制游戏期间的所有镜头,并打印一个圆圈表示每个镜头的套接字场。

代码语言:javascript
复制
#Creation of the Field with pre-stablished Length and Width
(fig,ax) = createPitch(pitchLengthX,pitchWidthY,'yards','gray')


for i,shot in shots.iterrows():
    x=shot['location'][0]
    y=shot['location'][1]
    
    goal=shot['shot_outcome_name']=='Goal'
    team_name=shot['team_name']
    
    circleSize=2
    circleSize=np.sqrt(shot['shot_statsbomb_xg'])*15

    if (team_name==home_team_required):
        if goal:
            shotCircle=plt.Circle((x,pitchWidthY-y),circleSize,color="red")
            plt.text((x+1),pitchWidthY-y+1,shot['player_name']) 
        else:
            shotCircle=plt.Circle((x,pitchWidthY-y),circleSize,color="red")     
            shotCircle.set_alpha(.2)
    elif (team_name==away_team_required):
        if goal:
            shotCircle=plt.Circle((pitchLengthX-x,y),circleSize,color="blue") 
            plt.text((pitchLengthX-x+1),y+1,shot['player_name']) 
        else:
            shotCircle=plt.Circle((pitchLengthX-x,y),circleSize,color="blue")      
            shotCircle.set_alpha(.2)
    ax.add_patch(shotCircle)
    
    
plt.text(5,75,away_team_required + ' shots') 
plt.text(80,75,home_team_required + ' shots') 
     
fig.set_size_inches(10, 7)
fig.savefig('Output/shots.pdf', dpi=100) 
plt.title("Tiros del "+home_team_required+" vs "+away_team_required)
plt.show()

另一方面,这是我在字段上绘制传递的代码。我使用相同的函数来绘制字段,并对以前的函数做了一些调整。

代码语言:javascript
复制
passes = df.loc[df['type_name'] == 'Pass'].set_index('id')

name_passes = "Sweden Women's"
for i,i_pass in passes.iterrows():
    x=i_pass['location'][0]
    y=i_pass['location'][1]
        
    if (i_pass['team_name']==name_passes):
        passCircle=plt.Circle((x,pitchWidthY-y),2,color="red")
        passCircle.set_alpha(.2)
        ax.add_patch(passCircle)
    
    
plt.text(5,75,name_passes+' shots') 
     
fig.set_size_inches(10, 7)
fig.savefig('Output/shots.pdf', dpi=100) 
plt.title("Pases de "+name_passes)
plt.show()

fisrt函数的输出如下:一张地图,上面有游戏的所有镜头

passes函数的输出如下:

一条没有信息的白色连衣裙

如果你们知道如何解决这个问题,我会非常感谢你们的帮助。

编辑:我没有像SHIMO指出的那样提供最小的生殖代码,这是我正在做我的情节的完整代码:

代码语言:javascript
复制
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

trayectoria="D:\\Semestre 3 Itam\\DAI\\Proyecto 2\\"
health=pd.read_csv(trayectoria+"Health.csv",encoding='UTF-8')
paisesH={}
listaPaisesH=["Angola","China","Mexico","Norway","Senegal"]
i=7
for p in health["TABLE 3. HEALTH"][7:209]:
    if p in listaPaisesH:
        paisesH[p]=i
    i+=1

print(paisesH)

basicInd=pd.read_csv(trayectoria+"BasicIndicators.csv",encoding='UTF-8')
paisesBI={}
listaPaisesBI=["Angola","China","Mexico","Norway","Senegal"]
i=5
for p in basicInd["Unnamed: 1"][5:207]:
    if p in listaPaisesBI:
        paisesBI[p]=i
    i+=1

print(paisesBI)

datosIMR={}
datosBSS={}
for (x,y) in paisesBI.items():
    datosIMR[x]=basicInd["Unnamed: 8"][y]

for (x,y) in paisesH.items():
    datosBSS[x]=health["Unnamed: 4"][y]
    
datosBSS_ar=[]
datosIMR_ar=[]
for x in datosBSS.keys():
    datosBSS_ar.append(int(datosBSS[x]))
    datosIMR_ar.append(int(datosIMR[x]))
    

pais=["Angola","China","Mexico","Norway","Senegal"]
plt.scatter(datosBSS_ar, datosIMR_ar,s=100, alpha=0.3, edgecolors='none')

for i,p in enumerate(pais):
    plt.annotate(p, (datosBSS_ar[i],datosIMR_ar[i]))

plt.legend()
plt.grid(True)

plt.title('Mortandad Infantil vs Uso de Sanitización Básica')
plt.xlabel('Porcentaje de la población con acceso a una Sanitización Básica')
plt.ylabel('Menores de 1 año que fallecen por cada 1000')

m, b = np.polyfit(datosBSS_ar, datosIMR_ar, 1)
x=np.array(datosBSS_ar)   
plt.plot(x, m*x + b)

plt.show()

'Histogramas'
for (x,y) in datosBSS.items():
    datosBSS[x]=int(datosBSS[x])
    
    
estadisticasBSS=datosBSS
estadisticasBSS['media']=np.mean(datosBSS_ar)
estadisticasBSS['mediana']=np.median(datosBSS_ar)
estadisticasBSS['maximo']= np.max(datosBSS_ar)
estadisticasBSS['minimo']= np.min(datosBSS_ar)
plt.bar(estadisticasBSS.keys(), estadisticasBSS.values(),width=0.95, color='g')
plt.title("Porcentaje de la población con acceso a una Sanitización Básica (%)")
plt.xlabel('Pais')
plt.ylabel('Porcentaje')
plt.xticks(rotation=90)


for (x,y) in datosIMR.items():
    datosIMR[x]=int(datosIMR[x])
estadisticasIMR=datosIMR
estadisticasIMR['media']=np.mean(datosIMR_ar)
estadisticasIMR['mediana']= np.median(datosIMR_ar)
estadisticasIMR['maximo']= max(datosIMR_ar)
estadisticasIMR['minimo']= min(datosIMR_ar)
plt.bar(estadisticasIMR.keys(), estadisticasIMR.values(),width=0.95, color='g')
plt.title("Menores de 1 año que fallecen por cada 1000")
plt.xlabel('Pais')
plt.ylabel('Cantidad de muertes por cada 1000 personas')
plt.xticks(rotation=90)
    

'Life Expectancy vs Use of basic drinking water services (%)'

trayectoria="D:\\Semestre 3 Itam\\DAI\\Proyecto 2\\"
lifeExp=pd.read_csv(trayectoria+"DemographicIndicators.csv",encoding='UTF-8')
paisesLE={}
listaPaisesLE=["Angola","China","Mexico","Norway","Senegal"]
i=7
for p in lifeExp["TABLE 6. DEMOGRAPHIC INDICATORS"][7:207]:
    if p in listaPaisesLE:
        paisesLE[p]=i
    i+=1

print(paisesLE)

health=pd.read_csv(trayectoria+"Health.csv",encoding='UTF-8')
paisesBWS={}
listaPaisesBWS=["Angola","China","Mexico","Norway","Senegal"]
i=7
for p in health["TABLE 3. HEALTH"][7:207]:
    if p in listaPaisesBWS:
        paisesBWS[p]=i
    i+=1

print(paisesBWS)


datosLE={}
datosBWS={}
for (x,y) in paisesBWS.items():
    datosBWS[x]=health["Unnamed: 1"][y]

for (x,y) in paisesLE.items():
    datosLE[x]=lifeExp["Unnamed: 15"][y]
    
datosLE_ar=[]
datosBWS_ar=[]
for x in datosBWS.keys():
    datosBWS_ar.append(int(datosBWS[x]))
    datosLE_ar.append(int(datosLE[x]))
    

pais=["Angola","China","Mexico","Norway","Senegal"]
plt.scatter(datosBWS_ar, datosLE_ar,s=100, alpha=0.3, edgecolors='none')

for i,p in enumerate(pais):
    plt.annotate(p, (datosBWS_ar[i], datosLE_ar[i]))

plt.grid(True)

plt.title('Expectativa de Vida vs Uso the servicios básicos de agua potable (%)')
plt.ylabel('Expectativa de Vida')
plt.xlabel('Uso the servicios básicos de agua potable (%)')

m, b = np.polyfit(datosBWS_ar, datosLE_ar, 1)
x=np.array(datosBWS_ar)   
plt.plot(x, m*x + b)

plt.show()

'Histogramas'
for (x,y) in datosBWS.items():
    datosBWS[x]=int(datosBWS[x])
    
    
estadisticasBWS=datosBWS
estadisticasBWS['media']=np.mean(datosBWS_ar)
estadisticasBWS['mediana']=np.median(datosBWS_ar)
estadisticasBWS['maximo']= np.max(datosBWS_ar)
estadisticasBWS['minimo']= np.min(datosBWS_ar)
plt.bar(estadisticasBWS.keys(), estadisticasBWS.values(),width=0.95, color='g')
plt.title("Uso the servicios básicos de agua potable (%)")
plt.xlabel('Pais')
plt.ylabel('Porcentaje')
plt.xticks(rotation=90)


for (x,y) in datosLE.items():
    datosLE[x]=int(datosLE[x])
    
estadisticasLE=datosLE
estadisticasLE['media']=np.mean(datosLE_ar)
estadisticasLE['mediana']= np.median(datosLE_ar)
estadisticasLE['maximo']= max(datosLE_ar)
estadisticasLE['minimo']= min(datosLE_ar)
plt.bar(estadisticasLE.keys(), estadisticasLE.values(),width=0.95, color='g')
plt.title("Expectativa de Vida")
plt.xlabel('Pais')
plt.ylabel('Años esperados de vida')
plt.xticks(rotation=90)

这是我要导入的FCPython文件,以便能够使用createPitch函数:

代码语言:javascript
复制
import matplotlib.pyplot as plt
from matplotlib.patches import Arc

def createPitch(length,width, unity,linecolor): # in meters

    """
    creates a plot in which the 'length' is the length of the pitch (goal to goal).
    And 'width' is the width of the pitch (sideline to sideline). 
    Fill in the unity in meters or in yards.

    """
    #Set unity
    if unity == "meters":
        # Set boundaries
        if length >= 120.5 or width >= 75.5:
            return(str("Field dimensions are too big for meters as unity, didn't you mean yards as unity?\
                       Otherwise the maximum length is 120 meters and the maximum width is 75 meters. Please try again"))
        #Run program if unity and boundaries are accepted
        else:
            #Create figure
            fig=plt.figure()
            #fig.set_size_inches(7, 5)
            ax=fig.add_subplot(1,1,1)
           
            #Pitch Outline & Centre Line
            plt.plot([0,0],[0,width], color=linecolor)
            plt.plot([0,length],[width,width], color=linecolor)
            plt.plot([length,length],[width,0], color=linecolor)
            plt.plot([length,0],[0,0], color=linecolor)
            plt.plot([length/2,length/2],[0,width], color=linecolor)
            
            #Left Penalty Area
            plt.plot([16.5 ,16.5],[(width/2 +16.5),(width/2-16.5)],color=linecolor)
            plt.plot([0,16.5],[(width/2 +16.5),(width/2 +16.5)],color=linecolor)
            plt.plot([16.5,0],[(width/2 -16.5),(width/2 -16.5)],color=linecolor)
            
            #Right Penalty Area
            plt.plot([(length-16.5),length],[(width/2 +16.5),(width/2 +16.5)],color=linecolor)
            plt.plot([(length-16.5), (length-16.5)],[(width/2 +16.5),(width/2-16.5)],color=linecolor)
            plt.plot([(length-16.5),length],[(width/2 -16.5),(width/2 -16.5)],color=linecolor)
            
            #Left 5-meters Box
            plt.plot([0,5.5],[(width/2+7.32/2+5.5),(width/2+7.32/2+5.5)],color=linecolor)
            plt.plot([5.5,5.5],[(width/2+7.32/2+5.5),(width/2-7.32/2-5.5)],color=linecolor)
            plt.plot([5.5,0.5],[(width/2-7.32/2-5.5),(width/2-7.32/2-5.5)],color=linecolor)
            
            #Right 5 -eters Box
            plt.plot([length,length-5.5],[(width/2+7.32/2+5.5),(width/2+7.32/2+5.5)],color=linecolor)
            plt.plot([length-5.5,length-5.5],[(width/2+7.32/2+5.5),width/2-7.32/2-5.5],color=linecolor)
            plt.plot([length-5.5,length],[width/2-7.32/2-5.5,width/2-7.32/2-5.5],color=linecolor)
            
            #Prepare Circles
            centreCircle = plt.Circle((length/2,width/2),9.15,color=linecolor,fill=False)
            centreSpot = plt.Circle((length/2,width/2),0.8,color=linecolor)
            leftPenSpot = plt.Circle((11,width/2),0.8,color=linecolor)
            rightPenSpot = plt.Circle((length-11,width/2),0.8,color=linecolor)
            
            #Draw Circles
            ax.add_patch(centreCircle)
            ax.add_patch(centreSpot)
            ax.add_patch(leftPenSpot)
            ax.add_patch(rightPenSpot)
            
            #Prepare Arcs
            leftArc = Arc((11,width/2),height=18.3,width=18.3,angle=0,theta1=308,theta2=52,color=linecolor)
            rightArc = Arc((length-11,width/2),height=18.3,width=18.3,angle=0,theta1=128,theta2=232,color=linecolor)
            
            #Draw Arcs
            ax.add_patch(leftArc)
            ax.add_patch(rightArc)
            #Axis titles

    #check unity again
    elif unity == "yards":
        #check boundaries again
        if length <= 95:
            return(str("Didn't you mean meters as unity?"))
        elif length >= 131 or width >= 101:
            return(str("Field dimensions are too big. Maximum length is 130, maximum width is 100"))
        #Run program if unity and boundaries are accepted
        else:
            #Create figure
            fig=plt.figure()
            #fig.set_size_inches(7, 5)
            ax=fig.add_subplot(1,1,1)
           
            #Pitch Outline & Centre Line
            plt.plot([0,0],[0,width], color=linecolor)
            plt.plot([0,length],[width,width], color=linecolor)
            plt.plot([length,length],[width,0], color=linecolor)
            plt.plot([length,0],[0,0], color=linecolor)
            plt.plot([length/2,length/2],[0,width], color=linecolor)
            
            #Left Penalty Area
            plt.plot([18 ,18],[(width/2 +18),(width/2-18)],color=linecolor)
            plt.plot([0,18],[(width/2 +18),(width/2 +18)],color=linecolor)
            plt.plot([18,0],[(width/2 -18),(width/2 -18)],color=linecolor)
            
            #Right Penalty Area
            plt.plot([(length-18),length],[(width/2 +18),(width/2 +18)],color=linecolor)
            plt.plot([(length-18), (length-18)],[(width/2 +18),(width/2-18)],color=linecolor)
            plt.plot([(length-18),length],[(width/2 -18),(width/2 -18)],color=linecolor)
            
            #Left 6-yard Box
            plt.plot([0,6],[(width/2+7.32/2+6),(width/2+7.32/2+6)],color=linecolor)
            plt.plot([6,6],[(width/2+7.32/2+6),(width/2-7.32/2-6)],color=linecolor)
            plt.plot([6,0],[(width/2-7.32/2-6),(width/2-7.32/2-6)],color=linecolor)
            
            #Right 6-yard Box
            plt.plot([length,length-6],[(width/2+7.32/2+6),(width/2+7.32/2+6)],color=linecolor)
            plt.plot([length-6,length-6],[(width/2+7.32/2+6),width/2-7.32/2-6],color=linecolor)
            plt.plot([length-6,length],[(width/2-7.32/2-6),width/2-7.32/2-6],color=linecolor)
            
            #Prepare Circles; 10 yards distance. penalty on 12 yards
            centreCircle = plt.Circle((length/2,width/2),10,color=linecolor,fill=False)
            centreSpot = plt.Circle((length/2,width/2),0.8,color=linecolor)
            leftPenSpot = plt.Circle((12,width/2),0.8,color=linecolor)
            rightPenSpot = plt.Circle((length-12,width/2),0.8,color=linecolor)
            
            #Draw Circles
            ax.add_patch(centreCircle)
            ax.add_patch(centreSpot)
            ax.add_patch(leftPenSpot)
            ax.add_patch(rightPenSpot)
            
            #Prepare Arcs
            leftArc = Arc((11,width/2),height=20,width=20,angle=0,theta1=312,theta2=48,color=linecolor)
            rightArc = Arc((length-11,width/2),height=20,width=20,angle=0,theta1=130,theta2=230,color=linecolor)
            
            #Draw Arcs
            ax.add_patch(leftArc)
            ax.add_patch(rightArc)
                
    #Tidy Axes
    plt.axis('off')
    
    return fig,ax

希望有帮助:)

EN

回答 1

Stack Overflow用户

发布于 2021-02-18 23:21:02

我似乎已经解决了这个问题。在执行Pass代码之前调用createPitch函数。谢谢

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66268067

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档