这个python案例显示被射门次数对比?

wen python案例 3

Python 案例:被射门次数对比

下面给你一个完整的 Python 案例,用于对比两支球队(或球员)被射门次数的差异,包含数据准备、可视化、分析。

这个python案例显示被射门次数对比?

基础版本:两队被射门次数对比

import matplotlib.pyplot as plt
import numpy as np
# 中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# 1. 数据:两支球队在不同比赛中的被射门次数
matches = ['第1场', '第2场', '第3场', '第4场', '第5场']
team_a = [12, 8, 15, 10, 9]   # A队被射门次数
team_b = [7, 11, 6, 14, 8]    # B队被射门次数
x = np.arange(len(matches))
width = 0.35
# 2. 绘制分组柱状图
fig, ax = plt.subplots(figsize=(10, 6))
bars1 = ax.bar(x - width/2, team_a, width, label='A队', color='#4C72B0')
bars2 = ax.bar(x + width/2, team_b, width, label='B队', color='#DD8452')
# 3. 数值标注
for bars in (bars1, bars2):
    for bar in bars:
        h = bar.get_height()
        ax.text(bar.get_x() + bar.get_width()/2, h + 0.2,
                f'{int(h)}', ha='center', fontsize=10)
# 4. 图表设置
ax.set_xlabel('比赛场次')
ax.set_ylabel('被射门次数')
ax.set_title('A队 vs B队 被射门次数对比')
ax.set_xticks(x)
ax.set_xticklabels(matches)
ax.legend()
ax.grid(axis='y', linestyle='--', alpha=0.4)
plt.tight_layout()
plt.show()

进阶版本:多维度分析

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# 1. 构造数据
data = {
    '球队': ['A队']*5 + ['B队']*5 + ['C队']*5,
    '场次': [f'第{i}场' for i in range(1, 6)] * 3,
    '被射门次数': [12, 8, 15, 10, 9,   # A队
                  7, 11, 6, 14, 8,   # B队
                  10, 9, 12, 7, 11]  # C队
}
df = pd.DataFrame(data)
# 2. 汇总统计
summary = df.groupby('球队')['被射门次数'].agg(['sum', 'mean', 'max', 'min'])
print("=== 被射门次数汇总 ===")
print(summary)
# 3. 可视化:箱线图 + 平均值
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
# 箱线图
sns.boxplot(data=df, x='球队', y='被射门次数', ax=axes[0], palette='Set2')
axes[0].set_title('各队被射门次数分布(箱线图)')
axes[0].grid(axis='y', linestyle='--', alpha=0.4)
# 均值柱状图
means = df.groupby('球队')['被射门次数'].mean()
axes[1].bar(means.index, means.values, color=['#4C72B0', '#DD8452', '#55A868'])
for i, v in enumerate(means.values):
    axes[1].text(i, v + 0.1, f'{v:.1f}', ha='center')
axes[1].set_title('各队平均被射门次数')
axes[1].set_ylabel('被射门次数')
axes[1].grid(axis='y', linestyle='--', alpha=0.4)
plt.tight_layout()
plt.show()

输出结果示例

汇总统计:

      sum  mean  max  min
球队                     
A队    54  10.8   15    8
B队    46   9.2   14    6
C队    49   9.8   12    7

图表:

  • 左图:箱线图,展示各队被射门次数的中位数、四分位数和异常值
  • 右图:柱状图,展示各队平均被射门次数

足球场景中的常见扩展指标

指标 含义 用途
被射门次数(Shots Against) 对手射门总数 反映防守压力
被射正次数(Shots on Target Against) 对手射正次数 反映门将压力
xGA(预期被进球) 对手射门质量加权 更精准评估防守
场均被射门 每场平均被射门 跨队对比

如果想加入射正次数对比,只需在数据里增加一列 被射正次数,用相同的分组柱状图逻辑即可:

df['被射正次数'] = [5, 3, 6, 4, 3, 2, 5, 2, 6, 3, 4, 3, 5, 2, 4]
# 然后用 seaborn 的 hue 参数即可自动分组
sns.barplot(data=df, x='球队', y='被射门次数', hue='场次')

需要我把它改成球员之间的对比,或者加入 xGA / 射正率等更专业的足球数据分析指标吗?

上一篇根据实时python案例,最终结果已无悬念吗?

下一篇当前分类已是最新一篇

抱歉,评论功能暂时关闭!