跟踪代码NOOB[PYTHON]之友的问题

2024-09-29 22:00:49 发布

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

我正在学习python代码,我有一些问题:

https://github.com/Slothfulwave612/Football-Analytics-Using-Python/blob/master/03.%20Analyzing%20Event%20Data/pass_map.py

我的dubt非常简单:

我想申请一个for expresion,以便将通行证代码应用于多场足球比赛

^{pr1}$

##计算通过精度 合格率=(合格率/(合格率+合格率))*100 通过acc=str(圆形(通过acc,2)) ##向绘图中添加文本 plt.text(20,85,“{}传球地图vs皇家马德里”。格式(球员姓名),fontsize=15) plt.text(20,82,'通过精度:{}'。格式(通过acc),fontsize=15) ##处理标签 句柄,标签=plt.gca()。获取\u图例\u句柄\u标签() by_label=dict(拉链(标签、把手)) plt.legend(by_label.values()、by_label.keys()、loc='best',bbox_to_anchor=(0.9,1,0,0),fontsize=12) ##编辑体形大小并保存 图设置尺寸英寸(12,8) fig.savefig({}passmap.png')格式(匹配id),dpi=200 ##展示情节 plt.show()

我编辑代码只是为了用for expresion分析多个匹配项。

P1TMP=[162051613116265] 对于P1TMP中的i:

结果是:

在第一张图像中,结果几乎是完美的,但这种过程的过滤器不起作用。

enter image description here

在第二个图像中,过程是第一个匹配过程和第二个匹配过程的混合。我只想要第二场比赛的传球。

enter image description here

第三种是1号+2号+3号的组合。我需要第三张通行证: enter image description here

提前感谢您的支持

致意


Tags: 代码imageforbyhere过程格式plt
1条回答
网友
1楼 · 发布于 2024-09-29 22:00:49

所以它将所有匹配项合并到1上,因为该图是在前一个图的顶部“绘制”的。还有一些事情你也需要改变

  1. 客场球队不会永远是皇家马德里,所以要保持活力
  2. 在图形文本中调整它,使其不总是“vs. Real Madrid"
  3. 将文件另存为动态文件,以便它们不会覆盖
  4. 使用plt.title()plt.suptitle()代替plt.text插入标题(如果您想在特定的x,y坐标处进行注释,这是很好的),它将居中放置,并使文本的布局更加美观
  5. 您可以在迭代时使用i来匹配id变量,但随后不会在循环中更改/包括该变量
  6. 这是主要问题:(fig,ax) = createPitch(pitch_length_X, pitch_width_Y,'yards','gray') 是创建“空白画布”进行绘图的内容。因此,在每次绘图之前都需要调用它。这就像抓取一张新的空白纸进行绘图。如果只使用第一张初始图纸,则所有内容都将在该1张图纸上进行。因此,将其移动到for循环中

代码

import matplotlib.pyplot as plt
import json
from pandas.io.json import json_normalize
from FCPython import createPitch

## Note Statsbomb data uses yards for their pitch dimensions
pitch_length_X = 120
pitch_width_Y = 80



## match id for our El Clasico
match_list = [16205, 16131, 16265]
teamA = 'Barcelona'  #< - adjusted here

for match_id in match_list:
    ## calling the function to create a pitch map
    ## yards is the unit for measurement and
    ## gray will be the line color of the pitch map
    (fig,ax) = createPitch(pitch_length_X, pitch_width_Y,'yards','gray') #< moved into for loop

    player_name = 'Lionel Andrés Messi Cuccittini'

    ## this is the name of our event data file for
    ## our required El Clasico
    file_name = str(match_id) + '.json'

    ## loading the required event data file
    my_data = json.load(open('Statsbomb/data/events/' + file_name, 'r', encoding='utf-8'))


    ## get the nested structure into a dataframe 
    ## store the dataframe in a dictionary with the match id as key
    df = json_normalize(my_data, sep='_').assign(match_id = file_name[:-5])
    teamB = [x for x in list(df['team_name'].unique()) if x != teamA ][0] #< - get other team name

    ## making the list of all column names
    column = list(df.columns)

    ## all the type names we have in our dataframe
    all_type_name = list(df['type_name'].unique())

    ## creating a data frame for pass
    ## and then removing the null values
    ## only listing the player_name in the dataframe
    pass_df = df.loc[df['type_name'] == 'Pass', :].copy()
    pass_df.dropna(inplace=True, axis=1)
    pass_df = pass_df.loc[pass_df['player_name'] == player_name, :]

    ## creating a data frame for ball receipt
    ## removing all the null values
    ## and only listing Barcelona players in the dataframe
    breceipt_df = df.loc[df['type_name'] == 'Ball Receipt*', :].copy()
    breceipt_df.dropna(inplace=True, axis=1)
    breceipt_df = breceipt_df.loc[breceipt_df['team_name'] == 'Barcelona', :]

    pass_comp, pass_no = 0, 0
    ## pass_comp: completed pass
    ## pass_no: unsuccessful pass

    ## iterating through the pass dataframe
    for row_num, passed in pass_df.iterrows():   

        if passed['player_name'] == player_name:
            ## for away side
            x_loc = passed['location'][0]
            y_loc = passed['location'][1]

            pass_id = passed['id']
            summed_result = sum(breceipt_df.iloc[:, 14].apply(lambda x: pass_id in x))

            if summed_result > 0:
                ## if pass made was successful
                color = 'blue'
                label = 'Successful'
                pass_comp += 1
            else:
                ## if pass made was unsuccessful
                color = 'red'
                label = 'Unsuccessful'
                pass_no += 1

            ## plotting circle at the player's position
            shot_circle = plt.Circle((pitch_length_X - x_loc, y_loc), radius=2, color=color, label=label)
            shot_circle.set_alpha(alpha=0.2)
            ax.add_patch(shot_circle)

            ## parameters for making the arrow
            pass_x = 120 - passed['pass_end_location'][0]
            pass_y = passed['pass_end_location'][1] 
            dx = ((pitch_length_X - x_loc) - pass_x)
            dy = y_loc - pass_y

            ## making an arrow to display the pass
            pass_arrow = plt.Arrow(pitch_length_X - x_loc, y_loc, -dx, -dy, width=1, color=color)

            ## adding arrow to the plot
            ax.add_patch(pass_arrow)

    ## computing pass accuracy
    pass_acc = (pass_comp / (pass_comp + pass_no)) * 100
    pass_acc = str(round(pass_acc, 2))

    ## adding text to the plot
    plt.suptitle('{} pass map vs {}'.format(player_name, teamB), fontsize=15) #<  make dynamic and change to suptitle
    plt.title('Pass Accuracy: {}'.format(pass_acc), fontsize=15) #<  change to title

    ## handling labels
    handles, labels = plt.gca().get_legend_handles_labels()
    by_label = dict(zip(labels, handles))
    plt.legend(by_label.values(), by_label.keys(), loc='best', bbox_to_anchor=(0.9, 1, 0, 0), fontsize=12)

    ## editing the figure size and saving it
    fig.set_size_inches(12, 8)
    fig.savefig('{} passmap.png'.format(match_id), dpi=200)  #<  dynamic file name

    ## showing the plot
    plt.show()

相关问题 更多 >

    热门问题