为什么我不能画这个?(PythonSoccer字段)

2024-05-14 21:57:28 发布

您现在位置:Python中文网/ 问答频道 /正文

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

这就是我目前遇到的代码。此代码绘制游戏中的所有射击,并打印一个足球场,其中圆圈表示每个射击

#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()

另一方面,这是我用于在字段上绘制过程的代码。我正在使用相同的函数来绘制字段,并且对之前的函数做了一些调整

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()

First函数的输出如下所示: A map with all the shots of the game

PASS函数的输出如下所示:

A white strip with no information

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

编辑:我没有像SHIMO指出的那样提供最低限度的生殖代码 这是我进行绘图的完整代码:


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)

这是我为了能够使用createPitch函数而导入的FCPython文件:

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

希望有帮助:)


Tags: inaddforplotnppltaxwidth

热门问题