提供给我一个excel的数据集
Download ▾
From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with gpt-4.1-2025-04-14’s answer.Jump to turn (15)
- 1提供给我一个excel的数据集
- 2提供给我一个excel的数据集 要求内容为英雄联盟
- 3根据您提供给我的数据集 给我做一个数据预处理 数据可视化过程 可视化呈现 源代码的呈现 我的数据集保存为了:“英雄联盟xlsx”
- 4提供给我一个的数据集 给我做一个数据预处理 数据可视化过程 可视化呈现 源代码的呈现 要求代码要能直接运行
- 5和上面你的方法一样 做一个有关英雄联盟的内容 要求还是能直接运行
- 6将数据集内容直接给我放到python代码中我要一步直接做完
- 7将代码稍微简单一点 视图不需要 那么多 重新给我写一个 刚才给我的视图无法在pycharm中展示
- 8AttributeErAttributeError: 'FigureCanvasInterAgg' object has no attribute 'tostr
- 9就按照这个形式 再给我做一个有关pubg的
- 10将上面的英雄联盟数据代码 再多俩个视图给我
- 11和上面一样的要求 要求有8个视图 直接能运行 做一个关于魔兽争霸的
- 12要求8个视图不同的类型
Assistant我无法直接提供Excel文件,但我可以为您创建一些示例数据,您可以将其复制到Excel中。以下是一个销售数据的示例:
产品销售数据示例
code
日期,产品名称,类别,数量,单价,销售额,地区
2024-01-01,笔记本电脑,电子产品,5,4500,22500,北京
2024-01-01,办公椅,办公用品,12,350,4200,上海
2024-01-02,打印机,电子产品,3,1200,3600,广州
2024-01-02,A4纸,办公用品,50,25,1250,北京
2024-01-03,鼠标,电子产品,20,65,1300,深圳
2024-01-03,键盘,电子产品,15,120,1800,上海
2024-01-04,台灯,办公用品,8,180,1440,广州
2024-01-05,U盘,电子产品,30,45,1350,北京
2024-01-05,笔记本,办公用品,100,15,1500,深圳
2024-01-06,显示器,电子产品,6,800,4800,上海
您可以:
- 将以上数据复制粘贴到Excel中
- 使用Excel的"数据"→"从文本/CSV"功能导入
如果您需要其他类型的数据集(如客户信息、库存管理、财务数据等),或者需要更多行的数据,请告诉我具体需求,我可以为您生成相应的示例数据。
另外,如果您想要找现成的数据集,可以访问:
- Kaggle (kaggle.com/datasets)
- UCI机器学习库
- 政府开放数据平台
- Google Dataset Search
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
13
提供给我一个excel的数据集 要求内容为英雄联盟
Assistant以下是一个英雄联盟英雄数据的示例数据集,您可以复制到Excel中:
英雄联盟英雄数据
code
英雄名称,英文名,主要角色,次要角色,攻击类型,资源类型,难度等级,生命值,法力值,攻击力,护甲,魔抗,移动速度,攻击范围,价格(蓝色精粹)
盖伦,Garen,战士,坦克,近战,无消耗,1,620,0,66,36,32,340,175,450
艾希,Ashe,射手,辅助,远程,法力,2,570,280,61,26,30,325,600,450
瑞兹,Ryze,法师,战士,远程,法力,3,575,300,58,22,36,340,550,450
提莫,Teemo,射手,刺客,远程,法力,2,528,267,54,24,30,330,500,1350
亚索,Yasuo,战士,刺客,近战,无消耗,3,490,0,60,30,32,345,175,6300
劫,Zed,刺客,战士,近战,能量,3,584,200,63,32,32,345,125,6300
金克丝,Jinx,射手,无,远程,法力,2,581,245,57,28,30,325,525,6300
卡特琳娜,Katarina,刺客,法师,近战,无消耗,3,602,0,58,28,32,340,125,3150
李青,Lee Sin,战士,刺客,近战,能量,3,575,200,68,33,32,345,125,4800
索拉卡,Soraka,辅助,法师,远程,法力,1,535,425,50,32,30,325,550,450
塔里克,Taric,辅助,坦克,近战,法力,2,575,300,55,40,32,340,150,1350
维恩,Vayne,射手,刺客,远程,法力,3,515,231,60,23,30,330,550,4800
泰达米尔,Tryndamere,战士,刺客,近战,怒气,2,625,100,69,33,32,345,125,1350
安妮,Annie,法师,辅助,远程,法力,1,524,418,50,19,30,335,625,450
艾克,Ekko,刺客,战士,近战,法力,3,585,280,58,32,32,340,125,6300
英雄联盟比赛数据示例
code
比赛ID,日期,队伍,对手,英雄,位置,击杀,死亡,助攻,补刀数,金币,游戏时长(分钟),胜负
001,2024-01-15,T1,GEN,艾希,ADC,8,2,12,285,15200,32,胜
001,2024-01-15,T1,GEN,李青,打野,6,3,15,125,12500,32,胜
001,2024-01-15,T1,GEN,瑞兹,中单,5,1,10,310,14800,32,胜
001,2024-01-15,T1,GEN,盖伦,上单,3,2,8,245,11200,32,胜
001,2024-01-15,T1,GEN,索拉卡,辅助,1,1,18,35,8500,32,胜
002,2024-01-16,DK,HLE,金克丝,ADC,12,4,8,298,16800,35,负
002,2024-01-16,DK,HLE,劫,中单,9,5,6,275,14200,35,负
002,2024-01-16,DK,HLE,泰达米尔,上单,4,6,5,268,12100,35,负
002,2024-01-16,DK,HLE,艾克,打野,7,7,10,145,13500,35,负
002,2024-01-16,DK,HLE,塔里克,辅助,0,4,15,42,7800,35,负
您可以:
- 直接复制以上数据到Excel
- 使用"数据"→"分列"功能将逗号分隔的数据转换为表格
- 根据需要添加更多英雄或比赛数据
如果您需要其他类型的英雄联盟数据(如装备信息、符文数据、段位分布等),请告诉我具体需求。
根据您提供给我的数据集 给我做一个数据预处理 数据可视化过程 可视化呈现 源代码的呈现 我的数据集保存为了:“英雄联盟xlsx”
Assistant我将为您提供一个完整的数据预处理和可视化分析的Python代码。假设您已经将两个数据集分别保存在Excel文件的不同工作表中。
提供给我一个的数据集 给我做一个数据预处理 数据可视化过程 可视化呈现 源代码的呈现 要求代码要能直接运行
Assistant我将为您提供一个完整的电商销售数据集,以及可以直接运行的数据预处理和可视化代码。
和上面你的方法一样 做一个有关英雄联盟的内容 要求还是能直接运行
Assistant我将为您创建一个完整的英雄联盟数据分析系统,包含英雄数据、比赛数据和玩家统计,代码可以直接运行。
将数据集内容直接给我放到python代码中我要一步直接做完
Assistant我将为您提供一个完整的Python代码,包含所有数据集,可以一步运行完成所有分析:
将代码稍微简单一点 视图不需要 那么多 重新给我写一个 刚才给我的视图无法在pycharm中展示
Assistant我将为您提供一个简化版的代码,减少视图数量并确保在PyCharm中能正常显示:
AttributeErAttributeError: 'FigureCanvasInterAgg' object has no attribute 'tostring_rgb'.
Assistant这个错误是matplotlib版本兼容性问题。我来提供一个修复版本的代码:
Assistant我为您创建一个PUBG(绝地求生)数据分析系统,格式与之前相同:
Assistant我将在原有的英雄联盟代码基础上添加两个新的视图,并调整布局:
和上面一样的要求 要求有8个视图 直接能运行 做一个关于魔兽争霸的
Assistant我为您创建一个魔兽争霸数据分析系统,包含8个视图:
Assistant我为您重新设计魔兽争霸数据分析系统,确保8个视图都是不同类型:
Assistant我为您重新设计PUBG数据分析系统,确保8个视图都是不同类型:
Assistant给我做一个三角洲行动的 要求和上面一样 视图做的简单一点 要非常简单的视图
Assistant我为您创建一个三角洲行动的数据分析系统,使用非常简单的视图:
Turns (15)
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib import font_manager
# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用于显示中文
plt.rcParams['axes.unicode_minus'] = False # 用于显示负号
# 1. 数据加载
print("=== 数据加载 ===")
try:
# 读取Excel文件的两个工作表
df_heroes = pd.read_excel('英雄联盟.xlsx', sheet_name='英雄数据')
df_matches = pd.read_excel('英雄联盟.xlsx', sheet_name='比赛数据')
print("数据加载成功!")
except:
print("如果文件读取失败,请确保文件名和工作表名正确")
# 2. 数据预处理
print("\n=== 数据预处理 ===")
# 查看数据基本信息
print("\n英雄数据信息:")
print(df_heroes.info())
print("\n比赛数据信息:")
print(df_matches.info())
# 检查缺失值
print("\n缺失值检查:")
print("英雄数据缺失值:\n", df_heroes.isnull().sum())
print("\n比赛数据缺失值:\n", df_matches.isnull().sum())
# 数据类型转换
df_matches['日期'] = pd.to_datetime(df_matches['日期'])
df_matches['胜负'] = df_matches['胜负'].map({'胜': 1, '负': 0})
# 计算KDA
df_matches['KDA'] = (df_matches['击杀'] + df_matches['助攻']) / np.maximum(df_matches['死亡'], 1)
# 计算每分钟补刀
df_matches['每分钟补刀'] = df_matches['补刀数'] / df_matches['游戏时长(分钟)']
# 计算每分钟金币
df_matches['每分钟金币'] = df_matches['金币'] / df_matches['游戏时长(分钟)']
# 3. 数据可视化
print("\n=== 数据可视化 ===")
# 创建图形布局
fig = plt.figure(figsize=(20, 15))
# 3.1 英雄角色分布
ax1 = plt.subplot(3, 3, 1)
role_counts = df_heroes['主要角色'].value_counts()
colors = plt.cm.Set3(range(len(role_counts)))
plt.pie(role_counts.values, labels=role_counts.index, autopct='%1.1f%%', colors=colors)
plt.title('英雄主要角色分布', fontsize=14, fontweight='bold')
# 3.2 英雄难度分布
ax2 = plt.subplot(3, 3, 2)
difficulty_counts = df_heroes['难度等级'].value_counts().sort_index()
bars = plt.bar(difficulty_counts.index, difficulty_counts.values, color=['green', 'yellow', 'red'])
plt.xlabel('难度等级')
plt.ylabel('英雄数量')
plt.title('英雄难度等级分布', fontsize=14, fontweight='bold')
for bar in bars:
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2., height,
f'{int(height)}', ha='center', va='bottom')
# 3.3 英雄属性雷达图
ax3 = plt.subplot(3, 3, 3, projection='polar')
# 选择几个代表性英雄
selected_heroes = ['盖伦', '艾希', '劫', '索拉卡']
attributes = ['生命值', '攻击力', '护甲', '魔抗', '移动速度']
# 数据标准化
for attr in attributes:
df_heroes[attr + '_norm'] = (df_heroes[attr] - df_heroes[attr].min()) / (df_heroes[attr].max() - df_heroes[attr].min())
angles = np.linspace(0, 2 * np.pi, len(attributes), endpoint=False).tolist()
angles += angles[:1]
for hero in selected_heroes:
hero_data = df_heroes[df_heroes['英雄名称'] == hero]
values = [hero_data[attr + '_norm'].values[0] for attr in attributes]
values += values[:1]
ax3.plot(angles, values, 'o-', linewidth=2, label=hero)
ax3.fill(angles, values, alpha=0.25)
ax3.set_xticks(angles[:-1])
ax3.set_xticklabels(attributes)
ax3.set_ylim(0, 1)
plt.legend(loc='upper right', bbox_to_anchor=(1.3, 1.1))
plt.title('英雄属性对比雷达图', fontsize=14, fontweight='bold', y=1.08)
# 3.4 位置胜率分析
ax4 = plt.subplot(3, 3, 4)
position_winrate = df_matches.groupby('位置')['胜负'].agg(['mean', 'count'])
positions = position_winrate.index
win_rates = position_winrate['mean']
colors = plt.cm.RdYlGn(win_rates)
bars = plt.bar(positions, win_rates, color=colors)
plt.ylim(0, 1)
plt.ylabel('胜率')
plt.title('各位置胜率分析', fontsize=14, fontweight='bold')
for i, bar in enumerate(bars):
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2., height + 0.01,
f'{height:.2%}\n(n={position_winrate["count"].iloc[i]})',
ha='center', va='bottom')
# 3.5 KDA分布箱线图
ax5 = plt.subplot(3, 3, 5)
df_matches.boxplot(column='KDA', by='位置', ax=ax5)
plt.suptitle('')
plt.title('各位置KDA分布', fontsize=14, fontweight='bold')
plt.ylabel('KDA')
# 3.6 击杀与助攻相关性
ax6 = plt.subplot(3, 3, 6)
plt.scatter(df_matches['击杀'], df_matches['助攻'],
c=df_matches['胜负'], cmap='coolwarm', alpha=0.6, s=100)
plt.xlabel('击杀数')
plt.ylabel('助攻数')
plt.title('击杀与助攻关系(颜色表示胜负)', fontsize=14, fontweight='bold')
plt.colorbar(label='胜负')
# 3.7 英雄使用频率
ax7 = plt.subplot(3, 3, 7)
hero_usage = df_matches['英雄'].value_counts().head(5)
plt.barh(hero_usage.index, hero_usage.values, color=plt.cm.viridis(np.linspace(0, 1, 5)))
plt.xlabel('使用次数')
plt.title('英雄使用频率TOP5', fontsize=14, fontweight='bold')
for i, v in enumerate(hero_usage.values):
plt.text(v + 0.1, i, str(v), va='center')
# 3.8 经济发育对比
ax8 = plt.subplot(3, 3, 8)
df_matches_win = df_matches[df_matches['胜负'] == 1]
df_matches_lose = df_matches[df_matches['胜负'] == 0]
plt.hist(df_matches_win['每分钟金币'], alpha=0.5, label='胜利', bins=20, color='green')
plt.hist(df_matches_lose['每分钟金币'], alpha=0.5, label='失败', bins=20, color='red')
plt.xlabel('每分钟金币')
plt.ylabel('频次')
plt.title('胜负方经济发育对比', fontsize=14, fontweight='bold')
plt.legend()
# 3.9 综合表现热力图
ax9 = plt.subplot(3, 3, 9)
# 创建数据透视表
pivot_data = df_matches.pivot_table(values='KDA', index='英雄', columns='位置', aggfunc='mean')
sns.heatmap(pivot_data, annot=True, fmt='.2f', cmap='YlOrRd', cbar_kws={'label': '平均KDA'})
plt.title('英雄在各位置的平均KDA表现', fontsize=14, fontweight='bold')
plt.tight_layout()
plt.savefig('英雄联盟数据分析.png', dpi=300, bbox_inches='tight')
plt.show()
# 4. 统计分析报告
print("\n=== 统计分析报告 ===")
print(f"\n1. 英雄池分析:")
print(f" - 总英雄数:{len(df_heroes)}")
print(f" - 主要角色分布:")
for role, count in role_counts.items():
print(f" {role}:{count} ({count/len(df_heroes)*100:.1f}%)")
print(f"\n2. 比赛数据分析:")
print(f" - 总比赛场次:{len(df_matches)}")
print(f" - 平均游戏时长:{df_matches['游戏时长(分钟)'].mean():.1f} 分钟")
print(f" - 平均KDA:{df_matches['KDA'].mean():.2f}")
print(f"\n3. 位置胜率排名:")
position_winrate_sorted = position_winrate.sort_values('mean', ascending=False)
for pos, row in position_winrate_sorted.iterrows():
print(f" {pos}:{row['mean']*100:.1f}% (样本数:{row['count']})")
print(f"\n4. 高KDA英雄TOP3:")
hero_kda = df_matches.groupby('英雄')['KDA'].mean().sort_values(ascending=False).head(3)
for hero, kda in hero_kda.items():
print(f" {hero}:{kda:.2f}")
# 5. 导出处理后的数据
print("\n=== 导出处理后的数据 ===")
with pd.ExcelWriter('英雄联盟_分析结果.xlsx') as writer:
df_heroes.to_excel(writer, sheet_name='英雄数据_处理后', index=False)
df_matches.to_excel(writer, sheet_name='比赛数据_处理后', index=False)
position_winrate.to_excel(writer, sheet_name='位置胜率统计')
hero_kda.to_frame('平均KDA').to_excel(writer, sheet_name='英雄KDA排名')
print("处理后的数据已保存到:英雄联盟_分析结果.xlsx")
使用说明:
bash
pip install pandas numpy matplotlib seaborn openpyxl
-
数据准备:
- 将英雄数据保存在Excel的第一个工作表,命名为"英雄数据"
- 将比赛数据保存在Excel的第二个工作表,命名为"比赛数据"
- 文件名保存为"英雄联盟.xlsx"
-
运行代码:
- 直接运行上述Python代码
- 程序会自动进行数据预处理和生成可视化图表
- 生成的图表会保存为"英雄联盟数据分析.png"
- 处理后的数据会保存为"英雄联盟_分析结果.xlsx"
可视化内容包括:
- 英雄角色分布饼图
- 英雄难度等级分布
- 英雄属性雷达图
- 各位置胜率分析
- KDA分布箱线图
- 击杀与助攻相关性散点图
- 英雄使用频率排行
- 胜负方经济发育对比
- 英雄在各位置的表现热力图
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime, timedelta
import warnings
warnings.filterwarnings('ignore')
# 设置中文字体和样式
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.style.use('seaborn-v0_8-darkgrid')
# ==================== 1. 创建数据集 ====================
print("=== 创建数据集 ===")
# 设置随机种子
np.random.seed(42)
# 创建日期范围
start_date = datetime(2024, 1, 1)
dates = [start_date + timedelta(days=x) for x in range(90)]
# 产品信息
products = {
'手机': {'category': '电子产品', 'base_price': 3000, 'cost': 2000},
'笔记本电脑': {'category': '电子产品', 'base_price': 5000, 'cost': 3500},
'耳机': {'category': '电子产品', 'base_price': 300, 'cost': 150},
'运动鞋': {'category': '服装', 'base_price': 600, 'cost': 300},
'T恤': {'category': '服装', 'base_price': 150, 'cost': 50},
'背包': {'category': '配饰', 'base_price': 200, 'cost': 80},
'手表': {'category': '配饰', 'base_price': 1000, 'cost': 500},
'化妆品': {'category': '美妆', 'base_price': 200, 'cost': 60},
'护肤品': {'category': '美妆', 'base_price': 300, 'cost': 100},
'图书': {'category': '文化用品', 'base_price': 50, 'cost': 20}
}
# 地区信息
regions = ['华东', '华南', '华北', '华中', '西南', '西北', '东北']
# 客户类型
customer_types = ['新客户', '老客户', 'VIP客户']
# 生成销售数据
sales_data = []
order_id = 1000
for date in dates:
# 周末销量增加
is_weekend = date.weekday() >= 5
daily_orders = np.random.randint(20, 40) if is_weekend else np.random.randint(10, 25)
for _ in range(daily_orders):
product = np.random.choice(list(products.keys()))
product_info = products[product]
# 价格波动
price_variation = np.random.uniform(0.9, 1.1)
unit_price = product_info['base_price'] * price_variation
# 数量(便宜的产品可能买更多)
if unit_price < 200:
quantity = np.random.choice([1, 2, 3, 4, 5], p=[0.3, 0.3, 0.2, 0.1, 0.1])
else:
quantity = np.random.choice([1, 2, 3], p=[0.7, 0.2, 0.1])
sales_data.append({
'订单ID': f'ORD{order_id}',
'日期': date,
'产品名称': product,
'产品类别': product_info['category'],
'单价': round(unit_price, 2),
'成本': product_info['cost'],
'数量': quantity,
'销售额': round(unit_price * quantity, 2),
'地区': np.random.choice(regions),
'客户类型': np.random.choice(customer_types, p=[0.5, 0.3, 0.2]),
'支付方式': np.random.choice(['支付宝', '微信', '信用卡', '现金'], p=[0.4, 0.3, 0.2, 0.1]),
'配送方式': np.random.choice(['快递', '自提'], p=[0.8, 0.2])
})
order_id += 1
# 创建DataFrame
df = pd.DataFrame(sales_data)
print(f"数据集创建完成!共 {len(df)} 条记录")
# ==================== 2. 数据预处理 ====================
print("\n=== 数据预处理 ===")
# 查看数据基本信息
print("\n数据集信息:")
print(df.info())
print("\n数据集前5行:")
print(df.head())
# 检查缺失值
print("\n缺失值检查:")
print(df.isnull().sum())
# 添加衍生特征
# 利润
df['利润'] = df['销售额'] - df['成本'] * df['数量']
df['利润率'] = (df['利润'] / df['销售额'] * 100).round(2)
# 时间特征
df['年份'] = df['日期'].dt.year
df['月份'] = df['日期'].dt.month
df['星期'] = df['日期'].dt.day_name()
df['是否周末'] = df['日期'].dt.weekday >= 5
# 订单等级(基于销售额)
df['订单等级'] = pd.cut(df['销售额'],
bins=[0, 500, 2000, 5000, float('inf')],
labels=['小额', '中额', '大额', '超大额'])
print("\n数据预处理完成!")
# ==================== 3. 数据统计分析 ====================
print("\n=== 数据统计分析 ===")
print(f"\n销售总览:")
print(f"总销售额:¥{df['销售额'].sum():,.2f}")
print(f"总利润:¥{df['利润'].sum():,.2f}")
print(f"平均订单金额:¥{df['销售额'].mean():.2f}")
print(f"平均利润率:{df['利润率'].mean():.2f}%")
# ==================== 4. 数据可视化 ====================
print("\n=== 数据可视化 ===")
# 创建图形布局
fig = plt.figure(figsize=(20, 16))
# 4.1 销售趋势图
ax1 = plt.subplot(3, 3, 1)
daily_sales = df.groupby('日期')['销售额'].sum()
plt.plot(daily_sales.index, daily_sales.values, 'b-', linewidth=2)
plt.fill_between(daily_sales.index, daily_sales.values, alpha=0.3)
plt.title('每日销售额趋势', fontsize=14, fontweight='bold')
plt.xlabel('日期')
plt.ylabel('销售额(元)')
plt.xticks(rotation=45)
# 4.2 产品类别销售占比
ax2 = plt.subplot(3, 3, 2)
category_sales = df.groupby('产品类别')['销售额'].sum()
colors = plt.cm.Set3(range(len(category_sales)))
plt.pie(category_sales.values, labels=category_sales.index, autopct='%1.1f%%',
colors=colors, startangle=90)
plt.title('产品类别销售占比', fontsize=14, fontweight='bold')
# 4.3 地区销售对比
ax3 = plt.subplot(3, 3, 3)
region_sales = df.groupby('地区')['销售额'].sum().sort_values(ascending=True)
bars = plt.barh(region_sales.index, region_sales.values,
color=plt.cm.viridis(np.linspace(0, 1, len(region_sales))))
plt.xlabel('销售额(元)')
plt.title('各地区销售额对比', fontsize=14, fontweight='bold')
for i, (region, value) in enumerate(region_sales.items()):
plt.text(value + 1000, i, f'¥{value:,.0f}', va='center')
# 4.4 热门产品TOP10
ax4 = plt.subplot(3, 3, 4)
product_sales = df.groupby('产品名称')['销售额'].sum().sort_values(ascending=False).head(10)
plt.bar(range(len(product_sales)), product_sales.values,
color=plt.cm.RdYlBu(np.linspace(0, 1, len(product_sales))))
plt.xticks(range(len(product_sales)), product_sales.index, rotation=45, ha='right')
plt.ylabel('销售额(元)')
plt.title('热门产品TOP10', fontsize=14, fontweight='bold')
for i, v in enumerate(product_sales.values):
plt.text(i, v + 1000, f'¥{v:,.0f}', ha='center', va='bottom')
# 4.5 客户类型分析
ax5 = plt.subplot(3, 3, 5)
customer_analysis = df.groupby('客户类型').agg({
'销售额': 'sum',
'订单ID': 'count'
}).rename(columns={'订单ID': '订单数'})
x = np.arange(len(customer_analysis))
width = 0.35
bars1 = plt.bar(x - width/2, customer_analysis['销售额']/1000, width, label='销售额(千元)')
bars2 = plt.bar(x + width/2, customer_analysis['订单数']*10, width, label='订单数(×10)')
plt.xlabel('客户类型')
plt.title('客户类型销售分析', fontsize=14, fontweight='bold')
plt.xticks(x, customer_analysis.index)
plt.legend()
# 4.6 支付方式分布
ax6 = plt.subplot(3, 3, 6)
payment_counts = df['支付方式'].value_counts()
explode = [0.1 if x == payment_counts.max() else 0 for x in payment_counts.values]
plt.pie(payment_counts.values, labels=payment_counts.index, autopct='%1.1f%%',
explode=explode, shadow=True)
plt.title('支付方式分布', fontsize=14, fontweight='bold')
# 4.7 周销售额箱线图
ax7 = plt.subplot(3, 3, 7)
df['周'] = df['日期'].dt.isocalendar().week
weekly_data = df.groupby(['周', '产品类别'])['销售额'].sum().reset_index()
sns.boxplot(x='产品类别', y='销售额', data=weekly_data)
plt.xticks(rotation=45)
plt.title('各类别产品周销售额分布', fontsize=14, fontweight='bold')
# 4.8 利润率分布
ax8 = plt.subplot(3, 3, 8)
plt.hist(df['利润率'], bins=30, color='green', alpha=0.7, edgecolor='black')
plt.axvline(df['利润率'].mean(), color='red', linestyle='dashed', linewidth=2,
label=f'平均值: {df["利润率"].mean():.1f}%')
plt.xlabel('利润率(%)')
plt.ylabel('频次')
plt.title('订单利润率分布', fontsize=14, fontweight='bold')
plt.legend()
# 4.9 销售热力图(周-产品类别)
ax9 = plt.subplot(3, 3, 9)
heatmap_data = df.pivot_table(values='销售额',
index=df['日期'].dt.day_name(),
columns='产品类别',
aggfunc='sum')
# 重新排序星期
weekday_order = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
heatmap_data = heatmap_data.reindex(weekday_order)
sns.heatmap(heatmap_data, annot=True, fmt='.0f', cmap='YlOrRd', cbar_kws={'label': '销售额'})
plt.title('星期-产品类别销售热力图', fontsize=14, fontweight='bold')
plt.ylabel('星期')
plt.tight_layout()
plt.savefig('电商销售数据分析.png', dpi=300, bbox_inches='tight')
plt.show()
# ==================== 5. 高级分析 ====================
print("\n=== 高级分析结果 ===")
# 5.1 产品盈利能力分析
print("\n产品盈利能力TOP5:")
product_profit = df.groupby('产品名称').agg({
'销售额': 'sum',
'利润': 'sum',
'利润率': 'mean'
}).sort_values('利润', ascending=False).head()
print(product_profit)
# 5.2 时间段分析
print("\n工作日vs周末销售对比:")
weekend_analysis = df.groupby('是否周末')['销售额'].agg(['sum', 'mean', 'count'])
weekend_analysis.index = ['工作日', '周末']
print(weekend_analysis)
# 5.3 地区-客户类型交叉分析
print("\n地区-客户类型销售矩阵:")
cross_analysis = pd.crosstab(df['地区'], df['客户类型'], values=df['销售额'], aggfunc='sum')
print(cross_analysis)
# 导出分析报告
print("\n=== 生成分析报告 ===")
report = f"""
电商销售数据分析报告
生成时间:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
1. 数据概览
- 分析期间:{df['日期'].min().strftime('%Y-%m-%d')} 至 {df['日期'].max().strftime('%Y-%m-%d')}
- 总订单数:{len(df)}
- 总销售额:¥{df['销售额'].sum():,.2f}
- 总利润:¥{df['利润'].sum():,.2f}
- 平均利润率:{df['利润率'].mean():.2f}%
2. 产品分析
- 最畅销产品:{product_sales.index[0]}(销售额:¥{product_sales.values[0]:,.2f})
- 最高利润产品:{product_profit.index[0]}(利润:¥{product_profit['利润'].values[0]:,.2f})
3. 地区分析
- 最佳销售地区:{region_sales.index[-1]}(销售额:¥{region_sales.values[-1]:,.2f})
4. 客户分析
- VIP客户贡献:{(df[df['客户类型']=='VIP客户']['销售额'].sum() / df['销售额'].sum() * 100):.1f}%
"""
print(report)
# 保存报告
with open('销售分析报告.txt', 'w', encoding='utf-8') as f:
f.write(report)
print("分析报告已保存到:销售分析报告.txt")
运行说明:
bash
# 安装必要的库
pip install pandas numpy matplotlib seaborn
-
直接运行:
- 复制上述代码到Python文件(如:
sales_analysis.py)
- 直接运行:
python sales_analysis.py
- 无需准备任何数据文件,代码会自动生成数据
-
输出内容:
- 控制台输出:数据统计和分析结果
- 图片文件:
电商销售数据分析.png(包含9个可视化图表)
- 文本报告:
销售分析报告.txt
-
可视化内容:
- 每日销售趋势
- 产品类别占比
- 地区销售对比
- 热门产品排行
- 客户类型分析
- 支付方式分布
- 周销售额箱线图
- 利润率分布
- 销售热力图
这个代码完全自包含,可以直接运行,无需任何外部数据文件!
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime, timedelta
import warnings
warnings.filterwarnings('ignore')
# 设置中文字体和样式
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.style.use('seaborn-v0_8-darkgrid')
# ==================== 1. 创建英雄联盟数据集 ====================
print("=== 创建英雄联盟数据集 ===")
# 设置随机种子
np.random.seed(42)
# 英雄信息库
heroes_info = {
# 上单英雄
'盖伦': {'role': '战士', 'position': '上单', 'difficulty': 1, 'type': '坦克', 'damage_type': 'AD'},
'瑞文': {'role': '战士', 'position': '上单', 'difficulty': 3, 'type': '战士', 'damage_type': 'AD'},
'奥恩': {'role': '坦克', 'position': '上单', 'difficulty': 2, 'type': '坦克', 'damage_type': 'AP'},
'剑姬': {'role': '战士', 'position': '上单', 'difficulty': 3, 'type': '战士', 'damage_type': 'AD'},
'纳尔': {'role': '战士', 'position': '上单', 'difficulty': 3, 'type': '战士', 'damage_type': 'AD'},
# 打野英雄
'李青': {'role': '战士', 'position': '打野', 'difficulty': 3, 'type': '刺客', 'damage_type': 'AD'},
'赵信': {'role': '战士', 'position': '打野', 'difficulty': 1, 'type': '战士', 'damage_type': 'AD'},
'千珏': {'role': '射手', 'position': '打野', 'difficulty': 3, 'type': '射手', 'damage_type': 'AD'},
'努努': {'role': '坦克', 'position': '打野', 'difficulty': 1, 'type': '坦克', 'damage_type': 'AP'},
'男枪': {'role': '射手', 'position': '打野', 'difficulty': 2, 'type': '射手', 'damage_type': 'AD'},
# 中单英雄
'佐伊': {'role': '法师', 'position': '中单', 'difficulty': 3, 'type': '刺客', 'damage_type': 'AP'},
'阿狸': {'role': '法师', 'position': '中单', 'difficulty': 2, 'type': '刺客', 'damage_type': 'AP'},
'劫': {'role': '刺客', 'position': '中单', 'difficulty': 3, 'type': '刺客', 'damage_type': 'AD'},
'辛德拉': {'role': '法师', 'position': '中单', 'difficulty': 2, 'type': '法师', 'damage_type': 'AP'},
'亚索': {'role': '战士', 'position': '中单', 'difficulty': 3, 'type': '战士', 'damage_type': 'AD'},
# ADC英雄
'艾希': {'role': '射手', 'position': 'ADC', 'difficulty': 1, 'type': '射手', 'damage_type': 'AD'},
'金克丝': {'role': '射手', 'position': 'ADC', 'difficulty': 2, 'type': '射手', 'damage_type': 'AD'},
'薇恩': {'role': '射手', 'position': 'ADC', 'difficulty': 3, 'type': '射手', 'damage_type': 'AD'},
'卡莎': {'role': '射手', 'position': 'ADC', 'difficulty': 2, 'type': '射手', 'damage_type': 'Hybrid'},
'霞': {'role': '射手', 'position': 'ADC', 'difficulty': 2, 'type': '射手', 'damage_type': 'AD'},
# 辅助英雄
'索拉卡': {'role': '辅助', 'position': '辅助', 'difficulty': 1, 'type': '辅助', 'damage_type': 'AP'},
'璐璐': {'role': '辅助', 'position': '辅助', 'difficulty': 2, 'type': '辅助', 'damage_type': 'AP'},
'锤石': {'role': '辅助', 'position': '辅助', 'difficulty': 3, 'type': '坦克', 'damage_type': 'AP'},
'洛': {'role': '辅助', 'position': '辅助', 'difficulty': 2, 'type': '辅助', 'damage_type': 'AP'},
'布隆': {'role': '辅助', 'position': '辅助', 'difficulty': 1, 'type': '坦克', 'damage_type': 'AD'}
}
# 段位信息
ranks = ['青铜', '白银', '黄金', '铂金', '钻石', '大师', '王者']
rank_weights = [0.25, 0.35, 0.20, 0.10, 0.06, 0.03, 0.01]
# 服务器
servers = ['艾欧尼亚', '祖安', '德玛西亚', '班德尔城', '皮尔特沃夫']
# 创建英雄数据DataFrame
heroes_data = []
for hero_name, info in heroes_info.items():
heroes_data.append({
'英雄名称': hero_name,
'主要角色': info['role'],
'常用位置': info['position'],
'难度等级': info['difficulty'],
'英雄类型': info['type'],
'伤害类型': info['damage_type'],
'基础生命值': np.random.randint(520, 650),
'基础攻击力': np.random.randint(50, 70),
'基础护甲': np.random.randint(20, 40),
'基础魔抗': np.random.randint(30, 35),
'移动速度': np.random.randint(325, 350),
'攻击范围': 550 if info['position'] == 'ADC' else (175 if info['damage_type'] == 'AD' else 525),
'蓝色精粹价格': np.random.choice([450, 1350, 3150, 4800, 6300], p=[0.1, 0.2, 0.3, 0.3, 0.1])
})
df_heroes = pd.DataFrame(heroes_data)
# 创建比赛数据
print("生成比赛数据...")
matches_data = []
match_id = 1000
# 生成30天的比赛数据
start_date = datetime(2024, 1, 1)
dates = [start_date + timedelta(days=x) for x in range(30)]
for date in dates:
# 每天生成10-20场比赛
daily_matches = np.random.randint(10, 20)
for _ in range(daily_matches):
# 生成一场完整的比赛(10个玩家)
match_id += 1
game_duration = np.random.randint(20, 45)
# 随机决定哪队获胜
winning_team = np.random.choice(['蓝色方', '红色方'])
# 为每个位置选择英雄
positions = ['上单', '打野', '中单', 'ADC', '辅助']
used_heroes = []
for team in ['蓝色方', '红色方']:
for position in positions:
# 选择适合该位置的英雄
available_heroes = [h for h, info in heroes_info.items()
if info['position'] == position and h not in used_heroes]
hero = np.random.choice(available_heroes)
used_heroes.append(hero)
# 生成玩家数据
is_winning_team = (team == winning_team)
# 根据胜负调整数据
if is_winning_team:
kills = np.random.poisson(4)
deaths = np.random.poisson(3)
assists = np.random.poisson(8)
cs = int(game_duration * np.random.uniform(6, 9))
gold = int(game_duration * np.random.uniform(350, 450))
else:
kills = np.random.poisson(3)
deaths = np.random.poisson(5)
assists = np.random.poisson(5)
cs = int(game_duration * np.random.uniform(4, 7))
gold = int(game_duration * np.random.uniform(250, 350))
# 根据位置调整数据
if position == '辅助':
cs = int(cs * 0.1)
assists = int(assists * 1.5)
gold = int(gold * 0.7)
elif position == 'ADC':
cs = int(cs * 1.2)
gold = int(gold * 1.1)
elif position == '打野':
cs = int(cs * 0.6)
assists = int(assists * 1.2)
matches_data.append({
'比赛ID': f'MATCH{match_id}',
'日期': date,
'玩家ID': f'Player{np.random.randint(1000, 9999)}',
'段位': np.random.choice(ranks, p=rank_weights),
'服务器': np.random.choice(servers),
'队伍': team,
'英雄': hero,
'位置': position,
'击杀': max(0, kills),
'死亡': max(0, deaths),
'助攻': max(0, assists),
'补刀数': cs,
'金币': gold,
'游戏时长': game_duration,
'胜负': '胜利' if is_winning_team else '失败',
'视野得分': np.random.randint(20, 60),
'参团率': np.random.uniform(0.4, 0.9),
'伤害占比': np.random.uniform(0.1, 0.35) if position != '辅助' else np.random.uniform(0.05, 0.15),
'承伤占比': np.random.uniform(0.2, 0.4) if position in ['上单', '辅助'] else np.random.uniform(0.1, 0.25),
'MVP': False
})
df_matches = pd.DataFrame(matches_data)
# 为每场比赛选出MVP(KDA最高的获胜方玩家)
df_matches['KDA'] = (df_matches['击杀'] + df_matches['助攻']) / np.maximum(df_matches['死亡'], 1)
for match_id in df_matches['比赛ID'].unique():
match_data = df_matches[df_matches['比赛ID'] == match_id]
winning_team = match_data[match_data['胜负'] == '胜利']['队伍'].iloc[0]
mvp_idx = match_data[match_data['队伍'] == winning_team]['KDA'].idxmax()
df_matches.loc[mvp_idx, 'MVP'] = True
print(f"数据集创建完成!")
print(f"- 英雄数据:{len(df_heroes)} 个英雄")
print(f"- 比赛数据:{len(df_matches)} 条记录,{len(df_matches['比赛ID'].unique())} 场比赛")
# ==================== 2. 数据预处理 ====================
print("\n=== 数据预处理 ===")
# 添加衍生特征
df_matches['KDA评分'] = df_matches['KDA'].apply(lambda x:
'Perfect' if x >= 10 else
'Excellent' if x >= 5 else
'Good' if x >= 3 else
'Average' if x >= 2 else 'Poor')
df_matches['每分钟金币'] = df_matches['金币'] / df_matches['游戏时长']
df_matches['每分钟补刀'] = df_matches['补刀数'] / df_matches['游戏时长']
df_matches['参战贡献'] = (df_matches['击杀'] + df_matches['助攻']) / (df_matches['游戏时长'] / 10)
# 英雄使用统计
hero_stats = df_matches.groupby('英雄').agg({
'胜负': lambda x: (x == '胜利').sum() / len(x),
'击杀': 'mean',
'死亡': 'mean',
'助攻': 'mean',
'KDA': 'mean',
'比赛ID': 'count'
}).round(2)
hero_stats.columns = ['胜率', '场均击杀', '场均死亡', '场均助攻', '场均KDA', '使用次数']
print("数据预处理完成!")
# ==================== 3. 数据可视化 ====================
print("\n=== 生成可视化图表 ===")
# 创建图形布局
fig = plt.figure(figsize=(24, 20))
# 3.1 英雄位置分布
ax1 = plt.subplot(4, 3, 1)
position_counts = df_heroes['常用位置'].value_counts()
colors = plt.cm.Set3(range(len(position_counts)))
wedges, texts, autotexts = plt.pie(position_counts.values, labels=position_counts.index,
autopct='%1.1f%%', colors=colors, startangle=90)
plt.title('英雄位置分布', fontsize=16, fontweight='bold', pad=20)
for autotext in autotexts:
autotext.set_color('white')
autotext.set_fontsize(12)
autotext.set_fontweight('bold')
# 3.2 段位分布
ax2 = plt.subplot(4, 3, 2)
rank_counts = df_matches.drop_duplicates('玩家ID')['段位'].value_counts()
rank_order = ['青铜', '白银', '黄金', '铂金', '钻石', '大师', '王者']
rank_counts = rank_counts.reindex(rank_order)
bars = plt.bar(rank_counts.index, rank_counts.values,
color=['#CD7F32', '#C0C0C0', '#FFD700', '#E5E4E2', '#B9F2FF', '#800080', '#FF0000'])
plt.xlabel('段位')
plt.ylabel('玩家数量')
plt.title('玩家段位分布', fontsize=16, fontweight='bold')
for bar in bars:
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2., height,
f'{int(height)}', ha='center', va='bottom', fontsize=10)
# 3.3 热门英雄TOP10
ax3 = plt.subplot(4, 3, 3)
hero_popularity = df_matches['英雄'].value_counts().head(10)
plt.barh(range(len(hero_popularity)), hero_popularity.values,
color=plt.cm.viridis(np.linspace(0, 1, len(hero_popularity))))
plt.yticks(range(len(hero_popularity)), hero_popularity.index)
plt.xlabel('使用次数')
plt.title('热门英雄TOP10', fontsize=16, fontweight='bold')
for i, v in enumerate(hero_popularity.values):
plt.text(v + 0.5, i, str(v), va='center', fontsize=10)
# 3.4 各位置平均KDA
ax4 = plt.subplot(4, 3, 4)
position_kda = df_matches.groupby('位置')['KDA'].mean().sort_values(ascending=True)
bars = plt.barh(position_kda.index, position_kda.values,
color=['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A', '#98D8C8'])
plt.xlabel('平均KDA')
plt.title('各位置平均KDA表现', fontsize=16, fontweight='bold')
for i, (pos, value) in enumerate(position_kda.items()):
plt.text(value + 0.02, i, f'{value:.2f}', va='center', fontsize=11)
# 3.5 胜率最高英雄TOP10
ax5 = plt.subplot(4, 3, 5)
hero_winrate = hero_stats[hero_stats['使用次数'] >= 5].sort_values('胜率', ascending=False).head(10)
bars = plt.bar(range(len(hero_winrate)), hero_winrate['胜率'],
color=plt.cm.RdYlGn(hero_winrate['胜率']))
plt.xticks(range(len(hero_winrate)), hero_winrate.index, rotation=45, ha='right')
plt.ylabel('胜率')
plt.title('胜率最高英雄TOP10(至少5场)', fontsize=16, fontweight='bold')
plt.ylim(0, 1)
for i, v in enumerate(hero_winrate['胜率']):
plt.text(i, v + 0.01, f'{v:.1%}', ha='center', va='bottom', fontsize=10)
# 3.6 游戏时长分布
ax6 = plt.subplot(4, 3, 6)
plt.hist(df_matches['游戏时长'], bins=25, color='skyblue', edgecolor='black', alpha=0.7)
plt.axvline(df_matches['游戏时长'].mean(), color='red', linestyle='dashed', linewidth=2,
label=f'平均时长: {df_matches["游戏时长"].mean():.1f}分钟')
plt.xlabel('游戏时长(分钟)')
plt.ylabel('场次')
plt.title('游戏时长分布', fontsize=16, fontweight='bold')
plt.legend()
# 3.7 KDA分布箱线图
ax7 = plt.subplot(4, 3, 7)
positions_order = ['上单', '打野', '中单', 'ADC', '辅助']
df_matches_ordered = df_matches.copy()
df_matches_ordered['位置'] = pd.Categorical(df_matches_ordered['位置'], categories=positions_order, ordered=True)
sns.boxplot(x='位置', y='KDA', data=df_matches_ordered.sort_values('位置'),
palette='Set2', order=positions_order)
plt.ylim(0, 10)
plt.title('各位置KDA分布箱线图', fontsize=16, fontweight='bold')
# 3.8 英雄难度vs胜率
ax8 = plt.subplot(4, 3, 8)
# 合并英雄数据和统计数据
hero_analysis = df_heroes.merge(hero_stats, left_on='英雄名称', right_index=True)
difficulty_winrate = hero_analysis.groupby('难度等级')['胜率'].mean()
bars = plt.bar(['简单(1)', '中等(2)', '困难(3)'], difficulty_winrate.values,
color=['green', 'yellow', 'red'], alpha=0.7)
plt.ylabel('平均胜率')
plt.title('英雄难度与胜率关系', fontsize=16, fontweight='bold')
for bar in bars:
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2., height,
f'{height:.1%}', ha='center', va='bottom', fontsize=11)
# 3.9 团队贡献热力图
ax9 = plt.subplot(4, 3, 9)
contribution_data = df_matches.pivot_table(
values='参团率',
index='位置',
columns='段位',
aggfunc='mean'
)[rank_order]
sns.heatmap(contribution_data.loc[positions_order], annot=True, fmt='.2f',
cmap='YlOrRd', cbar_kws={'label': '参团率'})
plt.title('各位置在不同段位的参团率', fontsize=16, fontweight='bold')
# 3.10 MVP分布
ax10 = plt.subplot(4, 3, 10)
mvp_by_position = df_matches[df_matches['MVP']]['位置'].value_counts()
mvp_by_position = mvp_by_position.reindex(positions_order)
plt.bar(mvp_by_position.index, mvp_by_position.values,
color=plt.cm.plasma(np.linspace(0, 1, len(mvp_by_position))))
plt.xlabel('位置')
plt.ylabel('MVP次数')
plt.title('各位置获得MVP次数', fontsize=16, fontweight='bold')
for i, v in enumerate(mvp_by_position.values):
plt.text(i, v + 0.5, str(v), ha='center', va='bottom', fontsize=10)
# 3.11 经济发育曲线
ax11 = plt.subplot(4, 3, 11)
for position in positions_order:
pos_data = df_matches[df_matches['位置'] == position]
economy_by_time = pos_data.groupby(pd.cut(pos_data['游戏时长'], bins=5))['每分钟金币'].mean()
plt.plot(range(len(economy_by_time)), economy_by_time.values,
marker='o', label=position, linewidth=2)
plt.xlabel('游戏阶段')
plt.ylabel('每分钟金币')
plt.title('各位置经济发育曲线', fontsize=16, fontweight='bold')
plt.legend()
plt.grid(True, alpha=0.3)
# 3.12 综合表现雷达图
ax12 = plt.subplot(4, 3, 12, projection='polar')
# 选择几个热门英雄进行对比
selected_heroes = hero_popularity.head(4).index
angles = np.linspace(0, 2 * np.pi, 5, endpoint=False).tolist()
angles += angles[:1]
metrics = ['胜率', '场均击杀', '场均死亡', '场均助攻', '场均KDA']
for hero in selected_heroes:
hero_data = hero_stats.loc[hero]
# 标准化数据
values = [
hero_data['胜率'],
hero_data['场均击杀'] / 10, # 标准化到0-1
1 - hero_data['场均死亡'] / 10, # 反转并标准化
hero_data['场均助攻'] / 15, # 标准化
hero_data['场均KDA'] / 5 # 标准化
]
values += values[:1]
ax12.plot(angles, values, 'o-', linewidth=2, label=hero)
ax12.fill(angles, values, alpha=0.15)
ax12.set_xticks(angles[:-1])
ax12.set_xticklabels(metrics, size=10)
ax12.set_ylim(0, 1)
plt.legend(loc='upper right', bbox_to_anchor=(1.3, 1.1))
plt.title('热门英雄综合表现对比', fontsize=16, fontweight='bold', y=1.08)
plt.tight_layout()
plt.savefig('英雄联盟数据分析.png', dpi=300, bbox_inches='tight')
plt.show()
# ==================== 4. 高级统计分析 ====================
print("\n=== 高级统计分析 ===")
# 4.1 最佳英雄组合
print("\n最受欢迎的英雄组合(同队):")
match_teams = df_matches.groupby(['比赛ID', '队伍'])['英雄'].apply(list).reset_index()
hero_pairs = []
for _, team in match_teams.iterrows():
heroes = team['英雄']
for i in range(len(heroes)):
for j in range(i+1, len(heroes)):
hero_pairs.append(tuple(sorted([heroes[i], heroes[j]])))
from collections import Counter
pair_counts = Counter(hero_pairs)
top_pairs = pair_counts.most_common(5)
for pair, count in top_pairs:
print(f" {pair[0]} + {pair[1]}: {count}次")
# 4.2 位置表现分析
print("\n各位置关键数据:")
position_analysis = df_matches.groupby('位置').agg({
'KDA': 'mean',
'每分钟金币': 'mean',
'每分钟补刀': 'mean',
'参团率': 'mean',
'伤害占比': 'mean',
'MVP': 'sum'
}).round(2)
print(position_analysis)
# 4.3 段位表现差异
print("\n不同段位玩家表现差异:")
rank_performance = df_matches.groupby('段位').agg({
'KDA': 'mean',
'每分钟补刀': 'mean',
'视野得分': 'mean'
}).round(2)
rank_performance = rank_performance.reindex(rank_order)
print(rank_performance)
# ==================== 5. 生成分析报告 ====================
print("\n=== 生成综合分析报告 ===")
report = f"""
英雄联盟数据分析报告
生成时间:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
一、数据概览
- 分析期间:{df_matches['日期'].min().strftime('%Y-%m-%d')} 至 {df_matches['日期'].max().strftime('%Y-%m-%d')}
- 总比赛场次:{len(df_matches['比赛ID'].unique())}
- 参与玩家数:{len(df_matches['玩家ID'].unique())}
- 英雄池大小:{len(df_heroes)}个英雄
二、英雄分析
1. 最受欢迎英雄:{hero_popularity.index[0]}(使用{hero_popularity.values[0]}次)
2. 胜率最高英雄:{hero_winrate.index[0]}(胜率{hero_winrate['胜率'].values[0]:.1%})
3. 平均KDA最高:{hero_stats.sort_values('场均KDA', ascending=False).index[0]}({hero_stats.sort_values('场均KDA', ascending=False)['场均KDA'].values[0]:.2f})
三、位置分析
1. 平均KDA最高位置:{position_kda.index[-1]}({position_kda.values[-1]:.2f})
2. MVP最多位置:{mvp_by_position.index[0]}({mvp_by_position.values[0]}次)
3. 经济发育最好:{position_analysis.sort_values('每分钟金币', ascending=False).index[0]}({position_analysis.sort_values('每分钟金币', ascending=False)['每分钟金币'].values[0]:.1f}金/分钟)
四、游戏特征
1. 平均游戏时长:{df_matches['游戏时长'].mean():.1f}分钟
2. 平均KDA:{df_matches['KDA'].mean():.2f}
3. 完美KDA(≥10)比例:{(df_matches['KDA'] >= 10).sum() / len(df_matches) * 100:.1f}%
五、段位分布
{rank_counts.to_string()}
六、建议
1. 新手推荐英雄:{df_heroes[df_heroes['难度等级']==1]['英雄名称'].values[0]}(难度1,胜率稳定)
2. 高端局热门:{df_matches[df_matches['段位'].isin(['大师', '王者'])]['英雄'].value_counts().index[0]}
3. 最佳位置推荐:{position_kda.index[-1]}(KDA表现最稳定)
"""
print(report)
# 保存报告
with open('英雄联盟分析报告.txt', 'w', encoding='utf-8') as f:
f.write(report)
print("\n分析报告已保存到:英雄联盟分析报告.txt")
# 保存处理后的数据
with pd.ExcelWriter('英雄联盟数据分析结果.xlsx', engine='openpyxl') as writer:
df_heroes.to_excel(writer, sheet_name='英雄数据', index=False)
df_matches.to_excel(writer, sheet_name='比赛数据', index=False)
hero_stats.to_excel(writer, sheet_name='英雄统计')
position_analysis.to_excel(writer, sheet_name='位置分析')
rank_performance.to_excel(writer, sheet_name='段位分析')
print("Excel文件已保存到:英雄联盟数据分析结果.xlsx")
运行说明:
bash
pip install pandas numpy matplotlib seaborn openpyxl
-
直接运行:
- 将代码保存为
lol_analysis.py
- 运行命令:
python lol_analysis.py
- 无需任何外部数据文件
-
输出内容:
- 图片文件:
英雄联盟数据分析.png(包含12个可视化图表)
- 文本报告:
英雄联盟分析报告.txt
- Excel文件:
英雄联盟数据分析结果.xlsx(包含5个工作表)
-
可视化内容:
- 英雄位置分布
- 玩家段位分布
- 热门英雄TOP10
- 各位置KDA表现
- 胜率最高英雄
- 游戏时长分布
- KDA分布箱线图
- 英雄难度与胜率关系
- 团队贡献热力图
- MVP位置分布
- 经济发育曲线
- 英雄综合表现雷达图
这个代码完全自包含,包含了英雄联盟的各个分析维度,可以直接运行并生成专业的数据分析报告!
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
import warnings
warnings.filterwarnings('ignore')
# 设置中文字体和样式
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.style.use('seaborn-v0_8-darkgrid')
print("=== 英雄联盟数据分析系统 ===")
print("正在加载数据...")
# ==================== 1. 内置数据集 ====================
# 英雄数据
heroes_data = {
'英雄名称': ['盖伦', '艾希', '瑞兹', '提莫', '亚索', '劫', '金克丝', '卡特琳娜', '李青', '索拉卡',
'塔里克', '薇恩', '泰达米尔', '安妮', '艾克', '佐伊', '阿狸', '锤石', '德莱文', '伊泽瑞尔',
'卡莎', '莫甘娜', '拉克丝', '努努', '赵信', '皇子', '盲僧', '男枪', '千珏', '酒桶'],
'英文名': ['Garen', 'Ashe', 'Ryze', 'Teemo', 'Yasuo', 'Zed', 'Jinx', 'Katarina', 'LeeSin', 'Soraka',
'Taric', 'Vayne', 'Tryndamere', 'Annie', 'Ekko', 'Zoe', 'Ahri', 'Thresh', 'Draven', 'Ezreal',
'Kaisa', 'Morgana', 'Lux', 'Nunu', 'XinZhao', 'JarvanIV', 'LeeSin', 'Graves', 'Kindred', 'Gragas'],
'主要角色': ['战士', '射手', '法师', '射手', '战士', '刺客', '射手', '刺客', '战士', '辅助',
'辅助', '射手', '战士', '法师', '刺客', '法师', '法师', '辅助', '射手', '射手',
'射手', '法师', '法师', '坦克', '战士', '战士', '战士', '射手', '射手', '坦克'],
'次要角色': ['坦克', '辅助', '战士', '刺客', '刺客', '战士', '', '法师', '刺客', '法师',
'坦克', '刺客', '刺客', '辅助', '战士', '刺客', '刺客', '坦克', '', '法师',
'刺客', '辅助', '辅助', '战士', '刺客', '坦克', '刺客', '', '刺客', '战士'],
'攻击类型': ['近战', '远程', '远程', '远程', '近战', '近战', '远程', '近战', '近战', '远程',
'近战', '远程', '近战', '远程', '近战', '远程', '远程', '近战', '远程', '远程',
'远程', '远程', '远程', '近战', '近战', '近战', '近战', '远程', '远程', '近战'],
'资源类型': ['无消耗', '法力', '法力', '法力', '无消耗', '能量', '法力', '无消耗', '能量', '法力',
'法力', '法力', '怒气', '法力', '法力', '法力', '法力', '法力', '法力', '法力',
'法力', '法力', '法力', '法力', '法力', '法力', '能量', '法力', '法力', '法力'],
'难度等级': [1, 2, 3, 2, 3, 3, 2, 3, 3, 1, 2, 3, 2, 1, 3, 3, 2, 3, 3, 2, 2, 1, 1, 1, 2, 2, 3, 2, 3, 2],
'生命值': [620, 570, 575, 528, 490, 584, 581, 602, 575, 535, 575, 515, 625, 524, 585, 526, 526, 560, 557, 530,
600, 559, 490, 540, 650, 571, 575, 551, 540, 583],
'法力值': [0, 280, 300, 267, 0, 200, 245, 0, 200, 425, 300, 231, 100, 418, 280, 340, 334, 273, 360, 375,
344, 340, 480, 280, 0, 0, 200, 0, 300, 400],
'攻击力': [66, 61, 58, 54, 60, 63, 57, 58, 68, 50, 55, 60, 69, 50, 58, 48, 53, 56, 60, 60,
59, 55, 53, 61, 66, 64, 68, 68, 65, 61],
'护甲': [36, 26, 22, 24, 30, 32, 28, 28, 33, 32, 40, 23, 33, 19, 32, 20, 21, 28, 29, 25,
28, 25, 18, 29, 38, 34, 33, 33, 29, 35],
'魔抗': [32, 30, 36, 30, 32, 32, 30, 32, 32, 30, 32, 30, 32, 30, 32, 30, 30, 30, 30, 30,
30, 30, 30, 32, 32, 32, 32, 32, 30, 32],
'移动速度': [340, 325, 340, 330, 345, 345, 325, 340, 345, 325, 340, 330, 345, 335, 340, 340, 330, 335, 330, 325,
335, 335, 330, 345, 345, 340, 345, 340, 325, 330],
'攻击范围': [175, 600, 550, 500, 175, 125, 525, 125, 125, 550, 150, 550, 125, 625, 125, 550, 550, 450, 550, 550,
525, 450, 550, 125, 175, 175, 125, 425, 500, 125],
'价格(蓝色精粹)': [450, 450, 450, 1350, 6300, 6300, 6300, 3150, 4800, 450, 1350, 4800, 1350, 450, 6300, 6300, 3150, 6300, 6300, 3150,
6300, 1350, 3150, 450, 1350, 4800, 4800, 6300, 6300, 3150]
}
# 比赛数据
matches_data = {
'比赛ID': ['M001', 'M001', 'M001', 'M001', 'M001', 'M001', 'M001', 'M001', 'M001', 'M001',
'M002', 'M002', 'M002', 'M002', 'M002', 'M002', 'M002', 'M002', 'M002', 'M002',
'M003', 'M003', 'M003', 'M003', 'M003', 'M003', 'M003', 'M003', 'M003', 'M003',
'M004', 'M004', 'M004', 'M004', 'M004', 'M004', 'M004', 'M004', 'M004', 'M004',
'M005', 'M005', 'M005', 'M005', 'M005', 'M005', 'M005', 'M005', 'M005', 'M005'],
'日期': ['2024-01-15'] * 10 + ['2024-01-16'] * 10 + ['2024-01-17'] * 10 + ['2024-01-18'] * 10 + ['2024-01-19'] * 10,
'队伍': ['T1', 'T1', 'T1', 'T1', 'T1', 'GEN', 'GEN', 'GEN', 'GEN', 'GEN'] * 5,
'英雄': ['艾希', '李青', '瑞兹', '盖伦', '索拉卡', '金克丝', '劫', '泰达米尔', '艾克', '塔里克',
'薇恩', '赵信', '佐伊', '亚索', '锤石', '德莱文', '男枪', '卡特琳娜', '努努', '莫甘娜',
'伊泽瑞尔', '千珏', '阿狸', '提莫', '拉克丝', '卡莎', '酒桶', '安妮', '皇子', '索拉卡',
'金克丝', '李青', '劫', '盖伦', '塔里克', '艾希', '艾克', '瑞兹', '泰达米尔', '锤石',
'德莱文', '赵信', '佐伊', '亚索', '莫甘娜', '薇恩', '男枪', '阿狸', '努努', '拉克丝'],
'位置': ['ADC', '打野', '中单', '上单', '辅助', 'ADC', '中单', '上单', '打野', '辅助'] * 5,
'击杀': [8, 6, 5, 3, 1, 12, 9, 4, 7, 0, 10, 5, 7, 6, 2, 11, 8, 5, 4, 1,
7, 9, 6, 4, 0, 13, 5, 8, 6, 1, 9, 7, 8, 2, 1, 11, 6, 5, 3, 2,
14, 4, 6, 7, 0, 10, 5, 9, 3, 1],
'死亡': [2, 3, 1, 2, 1, 4, 5, 6, 7, 4, 3, 4, 2, 5, 3, 2, 6, 3, 5, 2,
1, 3, 2, 4, 1, 5, 4, 3, 6, 3, 3, 2, 4, 3, 2, 4, 5, 1, 4, 4,
2, 3, 3, 4, 1, 3, 5, 2, 4, 2],
'助攻': [12, 15, 10, 8, 18, 8, 6, 5, 10, 15, 9, 11, 8, 7, 16, 7, 5, 9, 12, 14,
11, 8, 10, 6, 19, 6, 9, 7, 8, 17, 10, 12, 7, 9, 15, 8, 11, 9, 6, 13,
7, 13, 9, 8, 18, 9, 6, 8, 10, 16],
'补刀数': [285, 125, 310, 245, 35, 298, 275, 268, 145, 42, 302, 135, 290, 256, 38,
315, 142, 281, 128, 45, 278, 138, 295, 240, 40, 308, 130, 288, 150, 36,
295, 128, 302, 250, 41, 289, 141, 315, 262, 39, 320, 120, 298, 268, 43,
310, 136, 305, 125, 47],
'金币': [15200, 12500, 14800, 11200, 8500, 16800, 14200, 12100, 13500, 7800,
16100, 13200, 15300, 12800, 8900, 17200, 13800, 14500, 11900, 8200,
15500, 14100, 15800, 11500, 8700, 17500, 12900, 15100, 13600, 8400,
16300, 13400, 15600, 11800, 8600, 16900, 13700, 16200, 12400, 9100,
17800, 12200, 15400, 13900, 8800, 17100, 13100, 16000, 11600, 9200],
'游戏时长(分钟)': [32] * 10 + [35] * 10 + [30] * 10 + [33] * 10 + [38] * 10,
'胜负': ['胜', '胜', '胜', '胜', '胜', '负', '负', '负', '负', '负',
'胜', '胜', '胜', '胜', '胜', '负', '负', '负', '负', '负',
'负', '负', '负', '负', '负', '胜', '胜', '胜', '胜', '胜',
'胜', '胜', '胜', '胜', '胜', '负', '负', '负', '负', '负',
'胜', '胜', '胜', '胜', '胜', '负', '负', '负', '负', '负'],
'段位': ['钻石', '钻石', '铂金', '黄金', '白银', '钻石', '铂金', '黄金', '白银', '白银',
'大师', '钻石', '钻石', '铂金', '黄金', '大师', '钻石', '铂金', '黄金', '白银',
'王者', '大师', '钻石', '钻石', '铂金', '王者', '大师', '钻石', '铂金', '黄金',
'铂金', '铂金', '黄金', '黄金', '白银', '铂金', '黄金', '黄金', '白银', '青铜',
'钻石', '钻石', '铂金', '黄金', '白银', '钻石', '铂金', '黄金', '白银', '青铜']
}
# 创建DataFrame
df_heroes = pd.DataFrame(heroes_data)
df_matches = pd.DataFrame(matches_data)
# 转换日期格式
df_matches['日期'] = pd.to_datetime(df_matches['日期'])
print("数据加载完成!")
# ==================== 2. 数据预处理 ====================
print("\n=== 数据预处理 ===")
# 计算KDA
df_matches['KDA'] = (df_matches['击杀'] + df_matches['助攻']) / np.maximum(df_matches['死亡'], 1)
# 计算每分钟数据
df_matches['每分钟补刀'] = df_matches['补刀数'] / df_matches['游戏时长(分钟)']
df_matches['每分钟金币'] = df_matches['金币'] / df_matches['游戏时长(分钟)']
# 胜负转换为数值
df_matches['胜负_数值'] = df_matches['胜负'].map({'胜': 1, '负': 0})
# 添加KDA等级
df_matches['KDA等级'] = pd.cut(df_matches['KDA'],
bins=[0, 2, 3, 5, 10, float('inf')],
labels=['较差', '一般', '良好', '优秀', '完美'])
print("数据预处理完成!")
# ==================== 3. 数据可视化 ====================
print("\n=== 生成可视化图表 ===")
# 创建图形布局
fig = plt.figure(figsize=(24, 20))
# 3.1 英雄角色分布
ax1 = plt.subplot(4, 3, 1)
role_counts = df_heroes['主要角色'].value_counts()
colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A', '#98D8C8']
plt.pie(role_counts.values, labels=role_counts.index, autopct='%1.1f%%',
colors=colors, startangle=90, shadow=True)
plt.title('英雄主要角色分布', fontsize=16, fontweight='bold')
# 3.2 英雄难度分布
ax2 = plt.subplot(4, 3, 2)
difficulty_counts = df_heroes['难度等级'].value_counts().sort_index()
bars = plt.bar(['简单(1)', '中等(2)', '困难(3)'], difficulty_counts.values,
color=['#2ECC71', '#F39C12', '#E74C3C'], edgecolor='black', linewidth=2)
plt.xlabel('难度等级', fontsize=12)
plt.ylabel('英雄数量', fontsize=12)
plt.title('英雄难度等级分布', fontsize=16, fontweight='bold')
for bar in bars:
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2., height,
f'{int(height)}', ha='center', va='bottom', fontsize=12, fontweight='bold')
# 3.3 英雄属性雷达图
ax3 = plt.subplot(4, 3, 3, projection='polar')
selected_heroes = ['盖伦', '艾希', '劫', '索拉卡']
attributes = ['生命值', '攻击力', '护甲', '魔抗', '移动速度']
for attr in attributes:
df_heroes[attr + '_norm'] = (df_heroes[attr] - df_heroes[attr].min()) / (df_heroes[attr].max() - df_heroes[attr].min())
angles = np.linspace(0, 2 * np.pi, len(attributes), endpoint=False).tolist()
angles += angles[:1]
for hero in selected_heroes:
hero_data = df_heroes[df_heroes['英雄名称'] == hero]
values = [hero_data[attr + '_norm'].values[0] for attr in attributes]
values += values[:1]
ax3.plot(angles, values, 'o-', linewidth=2, label=hero, markersize=8)
ax3.fill(angles, values, alpha=0.25)
ax3.set_xticks(angles[:-1])
ax3.set_xticklabels(attributes, size=12)
ax3.set_ylim(0, 1)
plt.legend(loc='upper right', bbox_to_anchor=(1.3, 1.1))
plt.title('英雄属性对比雷达图', fontsize=16, fontweight='bold', y=1.08)
# 3.4 位置胜率分析
ax4 = plt.subplot(4, 3, 4)
position_winrate = df_matches.groupby('位置')['胜负_数值'].agg(['mean', 'count'])
positions = position_winrate.index
win_rates = position_winrate['mean']
colors = plt.cm.RdYlGn(win_rates)
bars = plt.bar(positions, win_rates, color=colors, edgecolor='black', linewidth=2)
plt.ylim(0, 1)
plt.ylabel('胜率', fontsize=12)
plt.title('各位置胜率分析', fontsize=16, fontweight='bold')
for i, bar in enumerate(bars):
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2., height + 0.01,
f'{height:.1%}\n(n={position_winrate["count"].iloc[i]})',
ha='center', va='bottom', fontsize=11)
# 3.5 KDA分布箱线图
ax5 = plt.subplot(4, 3, 5)
position_order = ['上单', '打野', '中单', 'ADC', '辅助']
df_matches_ordered = df_matches.copy()
df_matches_ordered['位置'] = pd.Categorical(df_matches_ordered['位置'], categories=position_order, ordered=True)
box_plot = df_matches_ordered.boxplot(column='KDA', by='位置', ax=ax5, patch_artist=True)
colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A', '#98D8C8']
for patch, color in zip(box_plot.artists, colors):
patch.set_facecolor(color)
plt.suptitle('')
plt.title('各位置KDA分布', fontsize=16, fontweight='bold')
plt.ylabel('KDA', fontsize=12)
plt.xlabel('位置', fontsize=12)
# 3.6 击杀与助攻相关性
ax6 = plt.subplot(4, 3, 6)
scatter = plt.scatter(df_matches['击杀'], df_matches['助攻'],
c=df_matches['胜负_数值'], cmap='coolwarm',
alpha=0.7, s=100, edgecolors='black', linewidth=1)
plt.xlabel('击杀数', fontsize=12)
plt.ylabel('助攻数', fontsize=12)
plt.title('击杀与助攻关系(红=胜,蓝=负)', fontsize=16, fontweight='bold')
plt.colorbar(scatter, label='胜负')
# 3.7 英雄使用频率
ax7 = plt.subplot(4, 3, 7)
hero_usage = df_matches['英雄'].value_counts().head(10)
bars = plt.barh(range(len(hero_usage)), hero_usage.values,
color=plt.cm.viridis(np.linspace(0, 1, len(hero_usage))))
plt.yticks(range(len(hero_usage)), hero_usage.index)
plt.xlabel('使用次数', fontsize=12)
plt.title('英雄使用频率TOP10', fontsize=16, fontweight='bold')
for i, v in enumerate(hero_usage.values):
plt.text(v + 0.1, i, str(v), va='center', fontsize=11)
# 3.8 经济发育对比
ax8 = plt.subplot(4, 3, 8)
df_matches_win = df_matches[df_matches['胜负'] == '胜']
df_matches_lose = df_matches[df_matches['胜负'] == '负']
plt.hist(df_matches_win['每分钟金币'], alpha=0.6, label='胜利', bins=15,
color='#2ECC71', edgecolor='black', linewidth=1)
plt.hist(df_matches_lose['每分钟金币'], alpha=0.6, label='失败', bins=15,
color='#E74C3C', edgecolor='black', linewidth=1)
plt.xlabel('每分钟金币', fontsize=12)
plt.ylabel('频次', fontsize=12)
plt.title('胜负方经济发育对比', fontsize=16, fontweight='bold')
plt.legend(fontsize=12)
# 3.9 段位分布
ax9 = plt.subplot(4, 3, 9)
rank_counts = df_matches['段位'].value_counts()
rank_order = ['青铜', '白银', '黄金', '铂金', '钻石', '大师', '王者']
rank_counts = rank_counts.reindex([r for r in rank_order if r in rank_counts.index])
colors_rank = ['#CD7F32', '#C0C0C0', '#FFD700', '#E5E4E2', '#B9F2FF', '#800080', '#FF0000']
bars = plt.bar(rank_counts.index, rank_counts.values,
color=[colors_rank[rank_order.index(r)] for r in rank_counts.index],
edgecolor='black', linewidth=2)
plt.xlabel('段位', fontsize=12)
plt.ylabel('玩家数量', fontsize=12)
plt.title('玩家段位分布', fontsize=16, fontweight='bold')
for bar in bars:
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2., height,
f'{int(height)}', ha='center', va='bottom', fontsize=11)
# 3.10 KDA等级分布
ax10 = plt.subplot(4, 3, 10)
kda_level_counts = df_matches['KDA等级'].value_counts()
level_order = ['较差', '一般', '良好', '优秀', '完美']
kda_level_counts = kda_level_counts.reindex(level_order)
colors_kda = ['#E74C3C', '#F39C12', '#F1C40F', '#2ECC71', '#9B59B6']
plt.pie(kda_level_counts.values, labels=kda_level_counts.index, autopct='%1.1f%%',
colors=colors_kda, startangle=90, explode=[0.1 if x == '完美' else 0 for x in kda_level_counts.index])
plt.title('KDA等级分布', fontsize=16, fontweight='bold')
# 3.11 游戏时长分布
ax11 = plt.subplot(4, 3, 11)
plt.hist(df_matches['游戏时长(分钟)'], bins=10, color='#3498DB',
edgecolor='black', alpha=0.7, linewidth=2)
plt.axvline(df_matches['游戏时长(分钟)'].mean(), color='red', linestyle='dashed',
linewidth=3, label=f'平均时长: {df_matches["游戏时长(分钟)"].mean():.1f}分钟')
plt.xlabel('游戏时长(分钟)', fontsize=12)
plt.ylabel('场次', fontsize=12)
plt.title('游戏时长分布', fontsize=16, fontweight='bold')
plt.legend(fontsize=12)
# 3.12 综合表现热力图
ax12 = plt.subplot(4, 3, 12)
pivot_data = df_matches.pivot_table(values='KDA', index='英雄', columns='位置', aggfunc='mean')
mask = pivot_data.isnull()
sns.heatmap(pivot_data, annot=True, fmt='.2f', cmap='YlOrRd',
cbar_kws={'label': '平均KDA'}, mask=mask, square=True,
linewidths=1, linecolor='black')
plt.title('英雄在各位置的平均KDA表现', fontsize=16, fontweight='bold')
plt.xlabel('位置', fontsize=12)
plt.ylabel('英雄', fontsize=12)
plt.tight_layout()
plt.savefig('英雄联盟数据分析_完整版.png', dpi=300, bbox_inches='tight')
plt.show()
# ==================== 4. 统计分析报告 ====================
print("\n=== 统计分析报告 ===")
print(f"\n1. 英雄池分析:")
print(f" - 总英雄数:{len(df_heroes)}")
print(f" - 主要角色分布:")
for role, count in role_counts.items():
print(f" {role}:{count} ({count/len(df_heroes)*100:.1f}%)")
print(f"\n2. 比赛数据分析:")
print(f" - 总比赛场次:{len(df_matches['比赛ID'].unique())}")
print(f" - 平均游戏时长:{df_matches['游戏时长(分钟)'].mean():.1f} 分钟")
print(f" - 平均KDA:{df_matches['KDA'].mean():.2f}")
print(f"\n3. 位置胜率排名:")
position_winrate_sorted = position_winrate.sort_values('mean', ascending=False)
for pos, row in position_winrate_sorted.iterrows():
print(f" {pos}:{row['mean']*100:.1f}% (样本数:{row['count']})")
print(f"\n4. 高KDA英雄TOP5:")
hero_kda = df_matches.groupby('英雄')['KDA'].mean().sort_values(ascending=False).head()
for hero, kda in hero_kda.items():
print(f" {hero}:{kda:.2f}")
print(f"\n5. 英雄使用率TOP5:")
for hero, count in hero_usage.head().items():
print(f" {hero}:{count}次 ({count/len(df_matches)*100:.1f}%)")
# 生成详细报告
report = f"""
=====================================
英雄联盟数据分析报告
生成时间:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
=====================================
一、数据概览
- 分析期间:{df_matches['日期'].min().strftime('%Y-%m-%d')} 至 {df_matches['日期'].max().strftime('%Y-%m-%d')}
- 总比赛场次:{len(df_matches['比赛ID'].unique())}
- 总数据记录:{len(df_matches)}
- 英雄池大小:{len(df_heroes)}个英雄
二、英雄分析
1. 最受欢迎英雄:{hero_usage.index[0]}(使用{hero_usage.values[0]}次)
2. 平均KDA最高:{hero_kda.index[0]}(KDA: {hero_kda.values[0]:.2f})
3. 英雄难度分布:
- 简单英雄:{difficulty_counts[1]}个
- 中等英雄:{difficulty_counts[2]}个
- 困难英雄:{difficulty_counts[3]}个
三、位置分析
1. 胜率最高位置:{position_winrate_sorted.index[0]}({position_winrate_sorted['mean'].values[0]*100:.1f}%)
2. 平均KDA最高位置:{df_matches.groupby('位置')['KDA'].mean().idxmax()}({df_matches.groupby('位置')['KDA'].mean().max():.2f})
四、游戏特征
1. 平均游戏时长:{df_matches['游戏时长(分钟)'].mean():.1f}分钟
2. 平均击杀数:{df_matches['击杀'].mean():.1f}
3. 平均死亡数:{df_matches['死亡'].mean():.1f}
4. 平均助攻数:{df_matches['助攻'].mean():.1f}
5. 平均KDA:{df_matches['KDA'].mean():.2f}
五、经济数据
1. 平均每分钟金币:{df_matches['每分钟金币'].mean():.1f}
2. 平均每分钟补刀:{df_matches['每分钟补刀'].mean():.2f}
3. 胜利方平均金币:{df_matches[df_matches['胜负']=='胜']['金币'].mean():.0f}
4. 失败方平均金币:{df_matches[df_matches['胜负']=='负']['金币'].mean():.0f}
六、段位分布
{rank_counts.to_string()}
七、建议
1. 新手推荐英雄:{df_heroes[df_heroes['难度等级']==1].sample(3)['英雄名称'].tolist()}
2. 高胜率位置:{position_winrate_sorted.index[0]}
3. 发育型英雄:高补刀、高经济英雄更容易获胜
"""
print("\n" + report)
# 保存报告
with open('英雄联盟分析报告_完整版.txt', 'w', encoding='utf-8') as f:
f.write(report)
print("\n分析报告已保存到:英雄联盟分析报告_完整版.txt")
# 导出处理后的数据
with pd.ExcelWriter('英雄联盟_分析结果_完整版.xlsx', engine='openpyxl') as writer:
df_heroes.to_excel(writer, sheet_name='英雄数据', index=False)
df_matches.to_excel(writer, sheet_name='比赛数据', index=False)
# 英雄统计
hero_stats = df_matches.groupby('英雄').agg({
'击杀': 'mean',
'死亡': 'mean',
'助攻': 'mean',
'KDA': 'mean',
'每分钟金币': 'mean',
'比赛ID': 'count'
}).round(2)
hero_stats.columns = ['场均击杀', '场均死亡', '场均助攻', '场均KDA', '场均金币/分', '使用次数']
hero_stats.to_excel(writer, sheet_name='英雄统计')
# 位置统计
position_stats = df_matches.groupby('位置').agg({
'胜负_数值': ['mean', 'count'],
'KDA': 'mean',
'每分钟金币': 'mean',
'每分钟补刀': 'mean'
}).round(2)
position_stats.to_excel(writer, sheet_name='位置统计')
print("Excel文件已保存到:英雄联盟_分析结果_完整版.xlsx")
print("\n=== 分析完成!===")
使用说明:
-
直接复制运行:
- 将上述代码完整复制
- 保存为
.py 文件(如:lol_analysis_complete.py)
- 直接运行:
python lol_analysis_complete.py
-
无需任何外部文件:
- 所有数据都已内置在代码中
- 不需要准备Excel文件或其他数据文件
-
输出文件:
英雄联盟数据分析_完整版.png - 包含12个可视化图表
英雄联盟分析报告_完整版.txt - 详细的文字分析报告
英雄联盟_分析结果_完整版.xlsx - 包含原始数据和统计结果的Excel文件
-
环境要求:
bash
pip install pandas numpy matplotlib seaborn openpyxl
这个代码包含了完整的英雄联盟数据集,可以直接运行,一步完成所有分析!
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
# 配置matplotlib在PyCharm中显示
plt.rcParams['font.sans-serif'] = ['SimHei'] # 中文显示
plt.rcParams['axes.unicode_minus'] = False # 负号显示
print("=== 英雄联盟数据分析系统(简化版)===")
# ==================== 1. 内置数据集 ====================
# 英雄数据
heroes_data = {
'英雄': ['盖伦', '艾希', '亚索', '劫', '金克丝', '李青', '索拉卡', '薇恩', '提莫', '拉克丝'],
'角色': ['战士', '射手', '战士', '刺客', '射手', '战士', '辅助', '射手', '射手', '法师'],
'位置': ['上单', 'ADC', '中单', '中单', 'ADC', '打野', '辅助', 'ADC', '上单', '中单'],
'难度': [1, 2, 3, 3, 2, 3, 1, 3, 2, 1],
'价格': [450, 450, 6300, 6300, 6300, 4800, 450, 4800, 1350, 3150]
}
# 比赛数据(简化版,30条记录)
matches_data = {
'日期': ['2024-01-15']*10 + ['2024-01-16']*10 + ['2024-01-17']*10,
'英雄': ['艾希', '李青', '亚索', '盖伦', '索拉卡', '金克丝', '劫', '薇恩', '提莫', '拉克丝']*3,
'位置': ['ADC', '打野', '中单', '上单', '辅助', 'ADC', '中单', 'ADC', '上单', '中单']*3,
'击杀': [8, 6, 9, 3, 1, 12, 10, 11, 4, 7, 5, 7, 8, 2, 0, 10, 9, 13, 3, 6, 7, 5, 11, 4, 2, 9, 8, 10, 5, 8],
'死亡': [2, 3, 5, 2, 1, 4, 3, 2, 6, 2, 4, 2, 4, 3, 2, 3, 5, 1, 5, 3, 3, 4, 2, 4, 1, 2, 3, 3, 4, 2],
'助攻': [12, 15, 6, 8, 18, 8, 7, 9, 5, 10, 10, 13, 8, 9, 16, 11, 5, 12, 6, 9, 11, 12, 7, 8, 15, 10, 9, 8, 7, 11],
'补刀': [285, 125, 278, 245, 35, 298, 265, 310, 220, 280, 275, 135, 290, 250, 40, 295, 270, 305, 235, 285, 280, 130, 302, 248, 38, 290, 275, 298, 242, 288],
'金币': [15200, 12500, 14800, 11200, 8500, 16800, 14500, 17200, 10800, 14200,
14900, 13200, 15100, 11500, 8800, 16200, 14100, 17500, 11000, 14600,
15500, 12800, 16900, 11800, 8600, 16500, 14300, 17100, 11300, 15200],
'时长': [32]*10 + [35]*10 + [30]*10,
'胜负': ['胜', '胜', '负', '胜', '胜', '负', '负', '胜', '负', '胜']*3,
'段位': ['钻石', '钻石', '铂金', '黄金', '白银', '钻石', '铂金', '大师', '黄金', '铂金']*3
}
# 创建DataFrame
df_heroes = pd.DataFrame(heroes_data)
df_matches = pd.DataFrame(matches_data)
# ==================== 2. 数据预处理 ====================
print("\n数据预处理中...")
# 计算KDA
df_matches['KDA'] = (df_matches['击杀'] + df_matches['助攻']) / df_matches['死亡'].replace(0, 1)
df_matches['每分钟金币'] = df_matches['金币'] / df_matches['时长']
df_matches['每分钟补刀'] = df_matches['补刀'] / df_matches['时长']
# ==================== 3. 创建6个核心可视化图表 ====================
print("\n生成可视化图表...")
# 创建2x3的子图布局
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
fig.suptitle('英雄联盟数据分析', fontsize=20, fontweight='bold')
# 图1:英雄角色分布饼图
ax1 = axes[0, 0]
role_counts = df_heroes['角色'].value_counts()
ax1.pie(role_counts.values, labels=role_counts.index, autopct='%1.1f%%', startangle=90)
ax1.set_title('英雄角色分布', fontsize=14)
# 图2:各位置平均KDA柱状图
ax2 = axes[0, 1]
position_kda = df_matches.groupby('位置')['KDA'].mean().sort_values()
bars = ax2.bar(position_kda.index, position_kda.values, color='skyblue')
ax2.set_title('各位置平均KDA', fontsize=14)
ax2.set_ylabel('KDA')
for bar in bars:
height = bar.get_height()
ax2.text(bar.get_x() + bar.get_width()/2., height,
f'{height:.2f}', ha='center', va='bottom')
# 图3:英雄使用频率TOP5
ax3 = axes[0, 2]
hero_usage = df_matches['英雄'].value_counts().head(5)
ax3.barh(hero_usage.index, hero_usage.values, color='lightgreen')
ax3.set_title('英雄使用频率TOP5', fontsize=14)
ax3.set_xlabel('使用次数')
# 图4:胜负与金币关系箱线图
ax4 = axes[1, 0]
df_matches.boxplot(column='每分钟金币', by='胜负', ax=ax4)
ax4.set_title('胜负方经济对比', fontsize=14)
ax4.set_xlabel('胜负')
ax4.set_ylabel('每分钟金币')
plt.sca(ax4)
plt.xticks([1, 2], ['失败', '胜利'])
# 图5:段位分布
ax5 = axes[1, 1]
rank_counts = df_matches['段位'].value_counts()
ax5.bar(rank_counts.index, rank_counts.values, color=['#CD7F32', '#FFD700', '#C0C0C0', '#B9F2FF', '#800080'])
ax5.set_title('玩家段位分布', fontsize=14)
ax5.set_ylabel('数量')
# 图6:KDA分布直方图
ax6 = axes[1, 2]
ax6.hist(df_matches['KDA'], bins=15, color='coral', edgecolor='black', alpha=0.7)
ax6.axvline(df_matches['KDA'].mean(), color='red', linestyle='dashed', linewidth=2)
ax6.set_title('KDA分布', fontsize=14)
ax6.set_xlabel('KDA值')
ax6.set_ylabel('频次')
ax6.text(df_matches['KDA'].mean() + 0.5, ax6.get_ylim()[1] * 0.8,
f'平均值: {df_matches["KDA"].mean():.2f}', fontsize=10)
# 调整布局
plt.tight_layout()
# 显示图表
plt.show()
# ==================== 4. 简化的统计报告 ====================
print("\n=== 数据分析报告 ===")
print(f"\n基础统计:")
print(f"- 英雄总数:{len(df_heroes)}")
print(f"- 比赛场次:{len(df_matches)}")
print(f"- 平均KDA:{df_matches['KDA'].mean():.2f}")
print(f"- 平均游戏时长:{df_matches['时长'].mean():.1f}分钟")
print(f"\n英雄使用TOP3:")
for i, (hero, count) in enumerate(hero_usage.head(3).items(), 1):
print(f"{i}. {hero}: {count}次")
print(f"\n位置KDA排名:")
for pos, kda in position_kda.items():
print(f"- {pos}: {kda:.2f}")
print(f"\n胜率分析:")
win_rate = (df_matches['胜负'] == '胜').mean()
print(f"- 总体胜率:{win_rate*100:.1f}%")
# 英雄胜率
hero_winrate = df_matches.groupby('英雄').apply(
lambda x: (x['胜负'] == '胜').sum() / len(x) * 100
).sort_values(ascending=False)
print(f"\n英雄胜率TOP3:")
for hero, wr in hero_winrate.head(3).items():
usage = hero_usage.get(hero, 0)
print(f"- {hero}: {wr:.1f}% (使用{usage}次)")
# ==================== 5. 保存结果 ====================
# 保存图表
plt.savefig('英雄联盟分析_简化版.png', dpi=150, bbox_inches='tight')
print(f"\n图表已保存为:英雄联盟分析_简化版.png")
# 保存数据到Excel
with pd.ExcelWriter('英雄联盟数据_简化版.xlsx', engine='openpyxl') as writer:
df_heroes.to_excel(writer, sheet_name='英雄数据', index=False)
df_matches.to_excel(writer, sheet_name='比赛数据', index=False)
# 添加统计汇总
summary_data = {
'统计项': ['英雄总数', '比赛场次', '平均KDA', '平均时长', '总体胜率'],
'数值': [len(df_heroes), len(df_matches), f"{df_matches['KDA'].mean():.2f}",
f"{df_matches['时长'].mean():.1f}分钟", f"{win_rate*100:.1f}%"]
}
pd.DataFrame(summary_data).to_excel(writer, sheet_name='统计汇总', index=False)
print(f"Excel文件已保存为:英雄联盟数据_简化版.xlsx")
# 生成简单的文本报告
report = f"""
英雄联盟数据分析报告(简化版)
生成时间:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
1. 数据概览
- 英雄数量:{len(df_heroes)}个
- 比赛记录:{len(df_matches)}条
2. 核心指标
- 平均KDA:{df_matches['KDA'].mean():.2f}
- 平均游戏时长:{df_matches['时长'].mean():.1f}分钟
- 平均每分钟金币:{df_matches['每分钟金币'].mean():.1f}
3. 热门英雄
- {hero_usage.index[0]}({hero_usage.values[0]}次)
- {hero_usage.index[1]}({hero_usage.values[1]}次)
- {hero_usage.index[2]}({hero_usage.values[2]}次)
4. 位置表现
- 最高KDA位置:{position_kda.index[-1]}({position_kda.values[-1]:.2f})
- 最低KDA位置:{position_kda.index[0]}({position_kda.values[0]:.2f})
"""
with open('英雄联盟分析报告_简化版.txt', 'w', encoding='utf-8') as f:
f.write(report)
print(f"报告已保存为:英雄联盟分析报告_简化版.txt")
print("\n=== 分析完成!===")
- 更少的图表:只有6个核心图表,布局简洁
- PyCharm友好:使用标准的
plt.show()确保在PyCharm中正常显示
- 数据量适中:30条比赛记录,10个英雄
- 代码更简洁:去掉了复杂的分析,保留核心功能
- 一键运行:所有数据内置,无需外部文件
bash
pip install pandas numpy matplotlib seaborn openpyxl
import pandas as pd
import numpy as np
import matplotlib
matplotlib.use('Agg') # 设置非交互式后端,避免错误
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
# 配置matplotlib
plt.rcParams['font.sans-serif'] = ['SimHei'] # 中文显示
plt.rcParams['axes.unicode_minus'] = False # 负号显示
print("=== 英雄联盟数据分析系统(修复版)===")
# ==================== 1. 内置数据集 ====================
# 英雄数据
heroes_data = {
'英雄': ['盖伦', '艾希', '亚索', '劫', '金克丝', '李青', '索拉卡', '薇恩', '提莫', '拉克丝'],
'角色': ['战士', '射手', '战士', '刺客', '射手', '战士', '辅助', '射手', '射手', '法师'],
'位置': ['上单', 'ADC', '中单', '中单', 'ADC', '打野', '辅助', 'ADC', '上单', '中单'],
'难度': [1, 2, 3, 3, 2, 3, 1, 3, 2, 1],
'价格': [450, 450, 6300, 6300, 6300, 4800, 450, 4800, 1350, 3150]
}
# 比赛数据(简化版,30条记录)
matches_data = {
'日期': ['2024-01-15']*10 + ['2024-01-16']*10 + ['2024-01-17']*10,
'英雄': ['艾希', '李青', '亚索', '盖伦', '索拉卡', '金克丝', '劫', '薇恩', '提莫', '拉克丝']*3,
'位置': ['ADC', '打野', '中单', '上单', '辅助', 'ADC', '中单', 'ADC', '上单', '中单']*3,
'击杀': [8, 6, 9, 3, 1, 12, 10, 11, 4, 7, 5, 7, 8, 2, 0, 10, 9, 13, 3, 6, 7, 5, 11, 4, 2, 9, 8, 10, 5, 8],
'死亡': [2, 3, 5, 2, 1, 4, 3, 2, 6, 2, 4, 2, 4, 3, 2, 3, 5, 1, 5, 3, 3, 4, 2, 4, 1, 2, 3, 3, 4, 2],
'助攻': [12, 15, 6, 8, 18, 8, 7, 9, 5, 10, 10, 13, 8, 9, 16, 11, 5, 12, 6, 9, 11, 12, 7, 8, 15, 10, 9, 8, 7, 11],
'补刀': [285, 125, 278, 245, 35, 298, 265, 310, 220, 280, 275, 135, 290, 250, 40, 295, 270, 305, 235, 285, 280, 130, 302, 248, 38, 290, 275, 298, 242, 288],
'金币': [15200, 12500, 14800, 11200, 8500, 16800, 14500, 17200, 10800, 14200,
14900, 13200, 15100, 11500, 8800, 16200, 14100, 17500, 11000, 14600,
15500, 12800, 16900, 11800, 8600, 16500, 14300, 17100, 11300, 15200],
'时长': [32]*10 + [35]*10 + [30]*10,
'胜负': ['胜', '胜', '负', '胜', '胜', '负', '负', '胜', '负', '胜']*3,
'段位': ['钻石', '钻石', '铂金', '黄金', '白银', '钻石', '铂金', '大师', '黄金', '铂金']*3
}
# 创建DataFrame
df_heroes = pd.DataFrame(heroes_data)
df_matches = pd.DataFrame(matches_data)
# ==================== 2. 数据预处理 ====================
print("\n数据预处理中...")
# 计算KDA
df_matches['KDA'] = (df_matches['击杀'] + df_matches['助攻']) / df_matches['死亡'].replace(0, 1)
df_matches['每分钟金币'] = df_matches['金币'] / df_matches['时长']
df_matches['每分钟补刀'] = df_matches['补刀'] / df_matches['时长']
# ==================== 3. 创建可视化图表 ====================
print("\n生成可视化图表...")
# 创建图形
plt.figure(figsize=(15, 10))
# 图1:英雄角色分布饼图
plt.subplot(2, 3, 1)
role_counts = df_heroes['角色'].value_counts()
plt.pie(role_counts.values, labels=role_counts.index, autopct='%1.1f%%', startangle=90)
plt.title('英雄角色分布', fontsize=14)
# 图2:各位置平均KDA柱状图
plt.subplot(2, 3, 2)
position_kda = df_matches.groupby('位置')['KDA'].mean().sort_values()
bars = plt.bar(position_kda.index, position_kda.values, color='skyblue')
plt.title('各位置平均KDA', fontsize=14)
plt.ylabel('KDA')
for i, (pos, value) in enumerate(position_kda.items()):
plt.text(i, value + 0.1, f'{value:.2f}', ha='center', va='bottom')
# 图3:英雄使用频率TOP5
plt.subplot(2, 3, 3)
hero_usage = df_matches['英雄'].value_counts().head(5)
plt.barh(hero_usage.index, hero_usage.values, color='lightgreen')
plt.title('英雄使用频率TOP5', fontsize=14)
plt.xlabel('使用次数')
for i, v in enumerate(hero_usage.values):
plt.text(v + 0.1, i, str(v), va='center')
# 图4:胜负与金币关系
plt.subplot(2, 3, 4)
win_gold = df_matches[df_matches['胜负'] == '胜']['每分钟金币']
lose_gold = df_matches[df_matches['胜负'] == '负']['每分钟金币']
plt.boxplot([lose_gold, win_gold], labels=['失败', '胜利'])
plt.title('胜负方经济对比', fontsize=14)
plt.ylabel('每分钟金币')
# 图5:段位分布
plt.subplot(2, 3, 5)
rank_counts = df_matches['段位'].value_counts()
rank_order = ['白银', '黄金', '铂金', '钻石', '大师']
rank_counts = rank_counts.reindex([r for r in rank_order if r in rank_counts.index])
colors = {'白银': '#C0C0C0', '黄金': '#FFD700', '铂金': '#E5E4E2', '钻石': '#B9F2FF', '大师': '#800080'}
bar_colors = [colors.get(r, 'gray') for r in rank_counts.index]
plt.bar(rank_counts.index, rank_counts.values, color=bar_colors)
plt.title('玩家段位分布', fontsize=14)
plt.ylabel('数量')
# 图6:KDA分布直方图
plt.subplot(2, 3, 6)
plt.hist(df_matches['KDA'], bins=15, color='coral', edgecolor='black', alpha=0.7)
mean_kda = df_matches['KDA'].mean()
plt.axvline(mean_kda, color='red', linestyle='dashed', linewidth=2)
plt.title('KDA分布', fontsize=14)
plt.xlabel('KDA值')
plt.ylabel('频次')
plt.text(mean_kda + 0.5, plt.gca().get_ylim()[1] * 0.8,
f'平均值: {mean_kda:.2f}', fontsize=10)
# 调整布局并保存
plt.suptitle('英雄联盟数据分析', fontsize=20, fontweight='bold')
plt.tight_layout()
# 保存图表(先保存,再显示)
plt.savefig('英雄联盟分析_简化版.png', dpi=150, bbox_inches='tight')
print(f"图表已保存为:英雄联盟分析_简化版.png")
# 尝试显示(如果失败也不影响程序运行)
try:
plt.show()
except:
print("图表无法在当前环境显示,但已保存为PNG文件")
# ==================== 4. 统计报告 ====================
print("\n=== 数据分析报告 ===")
print(f"\n基础统计:")
print(f"- 英雄总数:{len(df_heroes)}")
print(f"- 比赛场次:{len(df_matches)}")
print(f"- 平均KDA:{df_matches['KDA'].mean():.2f}")
print(f"- 平均游戏时长:{df_matches['时长'].mean():.1f}分钟")
print(f"\n英雄使用TOP3:")
for i, (hero, count) in enumerate(hero_usage.head(3).items(), 1):
print(f"{i}. {hero}: {count}次")
print(f"\n位置KDA排名:")
for pos, kda in position_kda.items():
print(f"- {pos}: {kda:.2f}")
print(f"\n胜率分析:")
win_rate = (df_matches['胜负'] == '胜').mean()
print(f"- 总体胜率:{win_rate*100:.1f}%")
# 英雄胜率
hero_winrate = df_matches.groupby('英雄').apply(
lambda x: (x['胜负'] == '胜').sum() / len(x) * 100
).sort_values(ascending=False)
print(f"\n英雄胜率TOP3:")
for hero, wr in hero_winrate.head(3).items():
usage = hero_usage.get(hero, 0)
print(f"- {hero}: {wr:.1f}% (使用{usage}次)")
# ==================== 5. 保存结果 ====================
# 保存数据到Excel
try:
with pd.ExcelWriter('英雄联盟数据_简化版.xlsx', engine='openpyxl') as writer:
df_heroes.to_excel(writer, sheet_name='英雄数据', index=False)
df_matches.to_excel(writer, sheet_name='比赛数据', index=False)
# 添加统计汇总
summary_data = {
'统计项': ['英雄总数', '比赛场次', '平均KDA', '平均时长', '总体胜率'],
'数值': [len(df_heroes), len(df_matches), f"{df_matches['KDA'].mean():.2f}",
f"{df_matches['时长'].mean():.1f}分钟", f"{win_rate*100:.1f}%"]
}
pd.DataFrame(summary_data).to_excel(writer, sheet_name='统计汇总', index=False)
print(f"Excel文件已保存为:英雄联盟数据_简化版.xlsx")
except Exception as e:
print(f"Excel保存失败:{e}")
# 生成文本报告
report = f"""
英雄联盟数据分析报告(简化版)
生成时间:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
1. 数据概览
- 英雄数量:{len(df_heroes)}个
- 比赛记录:{len(df_matches)}条
2. 核心指标
- 平均KDA:{df_matches['KDA'].mean():.2f}
- 平均游戏时长:{df_matches['时长'].mean():.1f}分钟
- 平均每分钟金币:{df_matches['每分钟金币'].mean():.1f}
3. 热门英雄
- {hero_usage.index[0]}({hero_usage.values[0]}次)
- {hero_usage.index[1]}({hero_usage.values[1]}次)
- {hero_usage.index[2]}({hero_usage.values[2]}次)
4. 位置表现
- 最高KDA位置:{position_kda.index[-1]}({position_kda.values[-1]:.2f})
- 最低KDA位置:{position_kda.index[0]}({position_kda.values[0]:.2f})
5. 段位分布
"""
# 添加段位统计
for rank, count in rank_counts.items():
report += f" - {rank}:{count}人\n"
try:
with open('英雄联盟分析报告_简化版.txt', 'w', encoding='utf-8') as f:
f.write(report)
print(f"报告已保存为:英雄联盟分析报告_简化版.txt")
except Exception as e:
print(f"报告保存失败:{e}")
print("\n=== 分析完成!===")
print("即使图表无法显示,所有结果已保存到文件中。")
- 添加了
matplotlib.use('Agg'):使用非交互式后端,避免显示错误
- 异常处理:添加了try-except块处理可能的错误
- 先保存后显示:确保即使显示失败,文件也能正常保存
- 简化了部分代码:减少可能出错的复杂操作
bash
# 更新matplotlib到最新版本
pip install --upgrade matplotlib
# 或者安装特定版本
pip install matplotlib==3.5.3
import pandas as pd
import numpy as np
import matplotlib
matplotlib.use('Agg') # 设置非交互式后端,避免错误
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
# 配置matplotlib
plt.rcParams['font.sans-serif'] = ['SimHei'] # 中文显示
plt.rcParams['axes.unicode_minus'] = False # 负号显示
print("=== PUBG数据分析系统 ===")
# ==================== 1. 内置数据集 ====================
# 武器数据
weapons_data = {
'武器名称': ['M416', 'AKM', 'SCAR-L', 'M24', 'AWM', 'UZI', 'Vector', 'S686', 'Pan', 'M249'],
'武器类型': ['突击步枪', '突击步枪', '突击步枪', '狙击枪', '狙击枪', '冲锋枪', '冲锋枪', '霰弹枪', '近战武器', '机枪'],
'子弹类型': ['5.56mm', '7.62mm', '5.56mm', '7.62mm', '.300马格南', '9mm', '.45ACP', '12号', '无', '5.56mm'],
'基础伤害': [43, 49, 43, 79, 105, 26, 31, 25, 80, 45],
'射速': [0.086, 0.1, 0.096, 1.8, 1.85, 0.048, 0.055, 0.2, 0, 0.075],
'弹匣容量': [30, 30, 30, 5, 5, 25, 25, 2, 0, 100],
'有效射程': [60, 60, 60, 100, 100, 25, 25, 15, 1, 75]
}
# 比赛数据(50条记录)
matches_data = {
'比赛ID': [f'MATCH{i:03d}' for i in range(1, 51)],
'日期': ['2024-01-15']*10 + ['2024-01-16']*10 + ['2024-01-17']*10 + ['2024-01-18']*10 + ['2024-01-19']*10,
'玩家ID': [f'Player{i%10 + 1}' for i in range(50)],
'地图': np.random.choice(['艾伦格', '米拉玛', '萨诺', '维寒迪'], 50),
'模式': np.random.choice(['单排', '双排', '四排'], 50, p=[0.2, 0.3, 0.5]),
'最终排名': np.random.randint(1, 101, 50),
'击杀数': np.random.poisson(2, 50),
'助攻数': np.random.poisson(1, 50),
'生存时间': np.random.randint(1, 35, 50),
'造成伤害': np.random.randint(50, 800, 50),
'移动距离': np.random.uniform(0.5, 8, 50),
'治疗次数': np.random.randint(0, 10, 50),
'爆头数': np.random.poisson(0.5, 50),
'载具摧毁': np.random.poisson(0.3, 50),
'主武器': np.random.choice(['M416', 'AKM', 'SCAR-L', 'M24', 'AWM', 'UZI', 'Vector', 'M249'], 50),
'段位': np.random.choice(['青铜', '白银', '黄金', '铂金', '钻石', '王牌', '战神'], 50,
p=[0.15, 0.25, 0.25, 0.20, 0.10, 0.04, 0.01])
}
# 调整数据逻辑:排名越高,击杀和伤害越多
for i in range(50):
if matches_data['最终排名'][i] <= 10: # 前10名
matches_data['击杀数'][i] = np.random.randint(3, 10)
matches_data['造成伤害'][i] = np.random.randint(400, 1200)
elif matches_data['最终排名'][i] <= 30: # 11-30名
matches_data['击杀数'][i] = np.random.randint(1, 5)
matches_data['造成伤害'][i] = np.random.randint(200, 600)
else: # 30名以后
matches_data['击杀数'][i] = np.random.randint(0, 3)
matches_data['造成伤害'][i] = np.random.randint(0, 300)
# 创建DataFrame
df_weapons = pd.DataFrame(weapons_data)
df_matches = pd.DataFrame(matches_data)
# ==================== 2. 数据预处理 ====================
print("\n数据预处理中...")
# 计算KD比率
df_matches['KD'] = df_matches['击杀数'] / np.maximum(100 - df_matches['最终排名'], 1)
# 计算平均伤害
df_matches['每分钟伤害'] = df_matches['造成伤害'] / np.maximum(df_matches['生存时间'], 1)
# 计算吃鸡率(第一名)
df_matches['吃鸡'] = (df_matches['最终排名'] == 1).astype(int)
# 计算前十率
df_matches['前十'] = (df_matches['最终排名'] <= 10).astype(int)
# 综合评分
df_matches['综合评分'] = (
df_matches['击杀数'] * 20 +
df_matches['造成伤害'] * 0.1 +
(101 - df_matches['最终排名']) * 2 +
df_matches['助攻数'] * 10
)
# ==================== 3. 创建可视化图表 ====================
print("\n生成可视化图表...")
# 创建图形
plt.figure(figsize=(15, 10))
# 图1:武器类型分布饼图
plt.subplot(2, 3, 1)
weapon_type_counts = df_weapons['武器类型'].value_counts()
colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A', '#98D8C8']
plt.pie(weapon_type_counts.values, labels=weapon_type_counts.index,
autopct='%1.1f%%', startangle=90, colors=colors[:len(weapon_type_counts)])
plt.title('武器类型分布', fontsize=14)
# 图2:地图胜率分析
plt.subplot(2, 3, 2)
map_winrate = df_matches.groupby('地图')['前十'].mean().sort_values()
bars = plt.bar(map_winrate.index, map_winrate.values, color='lightblue', edgecolor='navy')
plt.title('各地图前十率', fontsize=14)
plt.ylabel('前十率')
plt.ylim(0, 0.4)
for i, (map_name, value) in enumerate(map_winrate.items()):
plt.text(i, value + 0.01, f'{value:.1%}', ha='center', va='bottom')
# 图3:热门武器TOP5
plt.subplot(2, 3, 3)
weapon_usage = df_matches['主武器'].value_counts().head(5)
plt.barh(weapon_usage.index, weapon_usage.values, color='orange')
plt.title('热门武器TOP5', fontsize=14)
plt.xlabel('使用次数')
for i, v in enumerate(weapon_usage.values):
plt.text(v + 0.2, i, str(v), va='center')
# 图4:生存时间与击杀数关系
plt.subplot(2, 3, 4)
scatter = plt.scatter(df_matches['生存时间'], df_matches['击杀数'],
c=df_matches['最终排名'], cmap='RdYlGn_r',
s=60, alpha=0.6, edgecolors='black', linewidth=0.5)
plt.xlabel('生存时间(分钟)')
plt.ylabel('击杀数')
plt.title('生存时间与击杀数关系', fontsize=14)
plt.colorbar(scatter, label='最终排名')
# 图5:段位分布
plt.subplot(2, 3, 5)
rank_counts = df_matches['段位'].value_counts()
rank_order = ['青铜', '白银', '黄金', '铂金', '钻石', '王牌', '战神']
rank_counts = rank_counts.reindex([r for r in rank_order if r in rank_counts.index])
colors_rank = ['#CD7F32', '#C0C0C0', '#FFD700', '#E5E4E2', '#B9F2FF', '#800080', '#FF0000']
plt.bar(rank_counts.index, rank_counts.values,
color=[colors_rank[rank_order.index(r)] for r in rank_counts.index])
plt.title('玩家段位分布', fontsize=14)
plt.ylabel('人数')
plt.xticks(rotation=45)
for i, v in enumerate(rank_counts.values):
plt.text(i, v + 0.2, str(v), ha='center', va='bottom')
# 图6:游戏模式表现对比
plt.subplot(2, 3, 6)
mode_stats = df_matches.groupby('模式').agg({
'击杀数': 'mean',
'造成伤害': 'mean'
}).round(1)
x = np.arange(len(mode_stats))
width = 0.35
bars1 = plt.bar(x - width/2, mode_stats['击杀数'], width, label='平均击杀', color='red', alpha=0.7)
bars2 = plt.bar(x + width/2, mode_stats['造成伤害']/100, width, label='平均伤害(百)', color='blue', alpha=0.7)
plt.xlabel('游戏模式')
plt.title('不同模式表现对比', fontsize=14)
plt.xticks(x, mode_stats.index)
plt.legend()
# 添加数值标签
for bars in [bars1, bars2]:
for bar in bars:
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2., height,
f'{height:.1f}', ha='center', va='bottom', fontsize=9)
# 调整布局并保存
plt.suptitle('PUBG数据分析', fontsize=20, fontweight='bold')
plt.tight_layout()
# 保存图表
plt.savefig('PUBG数据分析.png', dpi=150, bbox_inches='tight')
print(f"图表已保存为:PUBG数据分析.png")
# 尝试显示
try:
plt.show()
except:
print("图表无法在当前环境显示,但已保存为PNG文件")
# ==================== 4. 统计报告 ====================
print("\n=== 数据分析报告 ===")
print(f"\n基础统计:")
print(f"- 总比赛场次:{len(df_matches)}")
print(f"- 武器种类:{len(df_weapons)}")
print(f"- 平均击杀数:{df_matches['击杀数'].mean():.2f}")
print(f"- 平均生存时间:{df_matches['生存时间'].mean():.1f}分钟")
print(f"- 平均伤害:{df_matches['造成伤害'].mean():.1f}")
print(f"\n吃鸡统计:")
winner_count = df_matches['吃鸡'].sum()
print(f"- 吃鸡次数:{winner_count}次")
print(f"- 吃鸡率:{winner_count/len(df_matches)*100:.1f}%")
print(f"- 前十率:{df_matches['前十'].mean()*100:.1f}%")
print(f"\n武器使用TOP3:")
for i, (weapon, count) in enumerate(weapon_usage.head(3).items(), 1):
damage = df_weapons[df_weapons['武器名称'] == weapon]['基础伤害'].values[0]
print(f"{i}. {weapon}: {count}次使用(基础伤害:{damage})")
print(f"\n地图表现排名:")
map_stats = df_matches.groupby('地图').agg({
'击杀数': 'mean',
'前十': 'mean'
}).round(2)
for map_name, stats in map_stats.iterrows():
print(f"- {map_name}: 平均击杀{stats['击杀数']:.1f}, 前十率{stats['前十']*100:.1f}%")
# 高手玩家分析
high_rank_players = df_matches[df_matches['段位'].isin(['王牌', '战神'])]
if len(high_rank_players) > 0:
print(f"\n高段位玩家表现:")
print(f"- 平均击杀:{high_rank_players['击杀数'].mean():.1f}")
print(f"- 平均伤害:{high_rank_players['造成伤害'].mean():.1f}")
print(f"- 吃鸡率:{high_rank_players['吃鸡'].mean()*100:.1f}%")
# ==================== 5. 保存结果 ====================
# 保存数据到Excel
try:
with pd.ExcelWriter('PUBG数据分析结果.xlsx', engine='openpyxl') as writer:
df_weapons.to_excel(writer, sheet_name='武器数据', index=False)
df_matches.to_excel(writer, sheet_name='比赛数据', index=False)
# 添加统计汇总
summary_data = {
'统计项': ['总比赛数', '平均击杀', '平均伤害', '吃鸡率', '前十率', '平均生存时间'],
'数值': [
len(df_matches),
f"{df_matches['击杀数'].mean():.2f}",
f"{df_matches['造成伤害'].mean():.1f}",
f"{winner_count/len(df_matches)*100:.1f}%",
f"{df_matches['前十'].mean()*100:.1f}%",
f"{df_matches['生存时间'].mean():.1f}分钟"
]
}
pd.DataFrame(summary_data).to_excel(writer, sheet_name='统计汇总', index=False)
# 武器排行
weapon_rank = df_matches['主武器'].value_counts().reset_index()
weapon_rank.columns = ['武器', '使用次数']
weapon_rank['使用率'] = (weapon_rank['使用次数'] / len(df_matches) * 100).round(1)
weapon_rank.to_excel(writer, sheet_name='武器排行', index=False)
print(f"Excel文件已保存为:PUBG数据分析结果.xlsx")
except Exception as e:
print(f"Excel保存失败:{e}")
# 生成文本报告
report = f"""
PUBG数据分析报告
生成时间:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
1. 数据概览
- 分析期间:{df_matches['日期'].min()} 至 {df_matches['日期'].max()}
- 比赛场次:{len(df_matches)}场
- 涉及玩家:{len(df_matches['玩家ID'].unique())}人
2. 核心指标
- 平均击杀数:{df_matches['击杀数'].mean():.2f}
- 平均伤害:{df_matches['造成伤害'].mean():.1f}
- 平均生存时间:{df_matches['生存时间'].mean():.1f}分钟
- 吃鸡率:{winner_count/len(df_matches)*100:.1f}%
- 前十率:{df_matches['前十'].mean()*100:.1f}%
3. 热门武器
- {weapon_usage.index[0]}({weapon_usage.values[0]}次)
- {weapon_usage.index[1]}({weapon_usage.values[1]}次)
- {weapon_usage.index[2]}({weapon_usage.values[2]}次)
4. 地图分析
"""
# 添加地图统计
for map_name, stats in map_stats.iterrows():
report += f" - {map_name}:平均击杀{stats['击杀数']:.1f},前十率{stats['前十']*100:.1f}%\n"
report += f"""
5. 段位分布
"""
for rank, count in rank_counts.items():
report += f" - {rank}:{count}人({count/len(df_matches)*100:.1f}%)\n"
# 添加最佳表现
best_match = df_matches.loc[df_matches['综合评分'].idxmax()]
report += f"""
6. 最佳单场表现
- 击杀数:{best_match['击杀数']}
- 造成伤害:{best_match['造成伤害']}
- 最终排名:第{best_match['最终排名']}名
- 使用武器:{best_match['主武器']}
"""
try:
with open('PUBG分析报告.txt', 'w', encoding='utf-8') as f:
f.write(report)
print(f"报告已保存为:PUBG分析报告.txt")
except Exception as e:
print(f"报告保存失败:{e}")
print("\n=== 分析完成!===")
print("所有分析结果已保存到相应文件中。")
-
武器数据:10种武器及其属性
-
比赛数据:50场比赛的详细记录
-
6个可视化图表:
- 武器类型分布
- 各地图前十率
- 热门武器TOP5
- 生存时间与击杀数关系
- 玩家段位分布
- 不同模式表现对比
-
统计分析:
- 吃鸡率、前十率
- 武器使用排行
- 地图表现分析
- 高段位玩家数据
-
输出文件:
- PUBG数据分析.png(可视化图表)
- PUBG数据分析结果.xlsx(详细数据)
- PUBG分析报告.txt(文字报告)
bash
pip install pandas numpy matplotlib seaborn openpyxl
import pandas as pd
import numpy as np
import matplotlib
matplotlib.use('Agg') # 设置非交互式后端,避免错误
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
# 配置matplotlib
plt.rcParams['font.sans-serif'] = ['SimHei'] # 中文显示
plt.rcParams['axes.unicode_minus'] = False # 负号显示
print("=== 英雄联盟数据分析系统(增强版)===")
# ==================== 1. 内置数据集 ====================
# 英雄数据
heroes_data = {
'英雄': ['盖伦', '艾希', '亚索', '劫', '金克丝', '李青', '索拉卡', '薇恩', '提莫', '拉克丝'],
'角色': ['战士', '射手', '战士', '刺客', '射手', '战士', '辅助', '射手', '射手', '法师'],
'位置': ['上单', 'ADC', '中单', '中单', 'ADC', '打野', '辅助', 'ADC', '上单', '中单'],
'难度': [1, 2, 3, 3, 2, 3, 1, 3, 2, 1],
'价格': [450, 450, 6300, 6300, 6300, 4800, 450, 4800, 1350, 3150]
}
# 比赛数据(简化版,30条记录)
matches_data = {
'日期': ['2024-01-15']*10 + ['2024-01-16']*10 + ['2024-01-17']*10,
'英雄': ['艾希', '李青', '亚索', '盖伦', '索拉卡', '金克丝', '劫', '薇恩', '提莫', '拉克丝']*3,
'位置': ['ADC', '打野', '中单', '上单', '辅助', 'ADC', '中单', 'ADC', '上单', '中单']*3,
'击杀': [8, 6, 9, 3, 1, 12, 10, 11, 4, 7, 5, 7, 8, 2, 0, 10, 9, 13, 3, 6, 7, 5, 11, 4, 2, 9, 8, 10, 5, 8],
'死亡': [2, 3, 5, 2, 1, 4, 3, 2, 6, 2, 4, 2, 4, 3, 2, 3, 5, 1, 5, 3, 3, 4, 2, 4, 1, 2, 3, 3, 4, 2],
'助攻': [12, 15, 6, 8, 18, 8, 7, 9, 5, 10, 10, 13, 8, 9, 16, 11, 5, 12, 6, 9, 11, 12, 7, 8, 15, 10, 9, 8, 7, 11],
'补刀': [285, 125, 278, 245, 35, 298, 265, 310, 220, 280, 275, 135, 290, 250, 40, 295, 270, 305, 235, 285, 280, 130, 302, 248, 38, 290, 275, 298, 242, 288],
'金币': [15200, 12500, 14800, 11200, 8500, 16800, 14500, 17200, 10800, 14200,
14900, 13200, 15100, 11500, 8800, 16200, 14100, 17500, 11000, 14600,
15500, 12800, 16900, 11800, 8600, 16500, 14300, 17100, 11300, 15200],
'时长': [32]*10 + [35]*10 + [30]*10,
'胜负': ['胜', '胜', '负', '胜', '胜', '负', '负', '胜', '负', '胜']*3,
'段位': ['钻石', '钻石', '铂金', '黄金', '白银', '钻石', '铂金', '大师', '黄金', '铂金']*3
}
# 创建DataFrame
df_heroes = pd.DataFrame(heroes_data)
df_matches = pd.DataFrame(matches_data)
# ==================== 2. 数据预处理 ====================
print("\n数据预处理中...")
# 计算KDA
df_matches['KDA'] = (df_matches['击杀'] + df_matches['助攻']) / df_matches['死亡'].replace(0, 1)
df_matches['每分钟金币'] = df_matches['金币'] / df_matches['时长']
df_matches['每分钟补刀'] = df_matches['补刀'] / df_matches['时长']
# ==================== 3. 创建8个可视化图表 ====================
print("\n生成可视化图表...")
# 创建图形 - 改为2x4布局
plt.figure(figsize=(20, 12))
# 图1:英雄角色分布饼图
plt.subplot(2, 4, 1)
role_counts = df_heroes['角色'].value_counts()
colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A', '#98D8C8']
plt.pie(role_counts.values, labels=role_counts.index, autopct='%1.1f%%',
startangle=90, colors=colors[:len(role_counts)])
plt.title('英雄角色分布', fontsize=14)
# 图2:各位置平均KDA柱状图
plt.subplot(2, 4, 2)
position_kda = df_matches.groupby('位置')['KDA'].mean().sort_values()
bars = plt.bar(position_kda.index, position_kda.values, color='skyblue')
plt.title('各位置平均KDA', fontsize=14)
plt.ylabel('KDA')
for i, (pos, value) in enumerate(position_kda.items()):
plt.text(i, value + 0.1, f'{value:.2f}', ha='center', va='bottom')
# 图3:英雄使用频率TOP5
plt.subplot(2, 4, 3)
hero_usage = df_matches['英雄'].value_counts().head(5)
plt.barh(hero_usage.index, hero_usage.values, color='lightgreen')
plt.title('英雄使用频率TOP5', fontsize=14)
plt.xlabel('使用次数')
for i, v in enumerate(hero_usage.values):
plt.text(v + 0.1, i, str(v), va='center')
# 图4:胜负与金币关系
plt.subplot(2, 4, 4)
win_gold = df_matches[df_matches['胜负'] == '胜']['每分钟金币']
lose_gold = df_matches[df_matches['胜负'] == '负']['每分钟金币']
plt.boxplot([lose_gold, win_gold], labels=['失败', '胜利'])
plt.title('胜负方经济对比', fontsize=14)
plt.ylabel('每分钟金币')
# 图5:段位分布
plt.subplot(2, 4, 5)
rank_counts = df_matches['段位'].value_counts()
rank_order = ['白银', '黄金', '铂金', '钻石', '大师']
rank_counts = rank_counts.reindex([r for r in rank_order if r in rank_counts.index])
colors = {'白银': '#C0C0C0', '黄金': '#FFD700', '铂金': '#E5E4E2', '钻石': '#B9F2FF', '大师': '#800080'}
bar_colors = [colors.get(r, 'gray') for r in rank_counts.index]
plt.bar(rank_counts.index, rank_counts.values, color=bar_colors)
plt.title('玩家段位分布', fontsize=14)
plt.ylabel('数量')
# 图6:KDA分布直方图
plt.subplot(2, 4, 6)
plt.hist(df_matches['KDA'], bins=15, color='coral', edgecolor='black', alpha=0.7)
mean_kda = df_matches['KDA'].mean()
plt.axvline(mean_kda, color='red', linestyle='dashed', linewidth=2)
plt.title('KDA分布', fontsize=14)
plt.xlabel('KDA值')
plt.ylabel('频次')
plt.text(mean_kda + 0.5, plt.gca().get_ylim()[1] * 0.8,
f'平均值: {mean_kda:.2f}', fontsize=10)
# 图7:不同段位的平均KDA对比(新增)
plt.subplot(2, 4, 7)
rank_kda = df_matches.groupby('段位')['KDA'].agg(['mean', 'std']).round(2)
# 按段位顺序排序
rank_kda = rank_kda.reindex([r for r in rank_order if r in rank_kda.index])
x = np.arange(len(rank_kda))
bars = plt.bar(x, rank_kda['mean'], yerr=rank_kda['std'],
color=['#C0C0C0', '#FFD700', '#E5E4E2', '#B9F2FF', '#800080'][:len(rank_kda)],
capsize=5, alpha=0.8)
plt.xticks(x, rank_kda.index)
plt.title('不同段位KDA表现', fontsize=14)
plt.ylabel('平均KDA')
for i, (idx, row) in enumerate(rank_kda.iterrows()):
plt.text(i, row['mean'] + row['std'] + 0.1, f"{row['mean']:.2f}",
ha='center', va='bottom')
# 图8:英雄胜率与使用率散点图(新增)
plt.subplot(2, 4, 8)
# 计算每个英雄的胜率和使用率
hero_stats = df_matches.groupby('英雄').agg({
'胜负': lambda x: (x == '胜').mean() * 100, # 胜率
'英雄': 'count' # 使用次数
}).rename(columns={'胜负': '胜率', '英雄': '使用次数'})
hero_stats['使用率'] = hero_stats['使用次数'] / len(df_matches) * 100
# 创建散点图
scatter = plt.scatter(hero_stats['使用率'], hero_stats['胜率'],
s=hero_stats['使用次数']*20,
alpha=0.6,
c=hero_stats['胜率'],
cmap='RdYlGn',
edgecolors='black',
linewidth=1)
# 添加英雄名称标签
for idx, row in hero_stats.iterrows():
plt.annotate(idx, (row['使用率'], row['胜率']),
xytext=(5, 5), textcoords='offset points', fontsize=9)
plt.xlabel('使用率 (%)')
plt.ylabel('胜率 (%)')
plt.title('英雄胜率与使用率分析', fontsize=14)
plt.grid(True, alpha=0.3)
# 添加平均线
plt.axhline(y=50, color='red', linestyle='--', alpha=0.5, label='50%胜率线')
plt.axvline(x=hero_stats['使用率'].mean(), color='blue', linestyle='--',
alpha=0.5, label='平均使用率')
plt.legend(loc='best', fontsize=8)
# 调整布局并保存
plt.suptitle('英雄联盟数据分析(增强版)', fontsize=20, fontweight='bold')
plt.tight_layout()
# 保存图表
plt.savefig('英雄联盟分析_增强版.png', dpi=150, bbox_inches='tight')
print(f"图表已保存为:英雄联盟分析_增强版.png")
# 尝试显示
try:
plt.show()
except:
print("图表无法在当前环境显示,但已保存为PNG文件")
# ==================== 4. 统计报告(更新版)====================
print("\n=== 数据分析报告 ===")
print(f"\n基础统计:")
print(f"- 英雄总数:{len(df_heroes)}")
print(f"- 比赛场次:{len(df_matches)}")
print(f"- 平均KDA:{df_matches['KDA'].mean():.2f}")
print(f"- 平均游戏时长:{df_matches['时长'].mean():.1f}分钟")
print(f"\n英雄使用TOP3:")
for i, (hero, count) in enumerate(hero_usage.head(3).items(), 1):
win_rate = (df_matches[df_matches['英雄'] == hero]['胜负'] == '胜').mean() * 100
print(f"{i}. {hero}: {count}次 (胜率{win_rate:.1f}%)")
print(f"\n位置KDA排名:")
for pos, kda in position_kda.items():
print(f"- {pos}: {kda:.2f}")
print(f"\n段位KDA分析:")
for rank, row in rank_kda.iterrows():
print(f"- {rank}: 平均KDA {row['mean']:.2f} (标准差±{row['std']:.2f})")
print(f"\n英雄胜率TOP3:")
hero_winrate = hero_stats.sort_values('胜率', ascending=False)
for hero, stats in hero_winrate.head(3).iterrows():
print(f"- {hero}: {stats['胜率']:.1f}% (使用{int(stats['使用次数'])}次)")
# ==================== 5. 保存结果 ====================
# 保存数据到Excel
try:
with pd.ExcelWriter('英雄联盟数据_增强版.xlsx', engine='openpyxl') as writer:
df_heroes.to_excel(writer, sheet_name='英雄数据', index=False)
df_matches.to_excel(writer, sheet_name='比赛数据', index=False)
# 添加统计汇总
summary_data = {
'统计项': ['英雄总数', '比赛场次', '平均KDA', '平均时长', '总体胜率'],
'数值': [len(df_heroes), len(df_matches), f"{df_matches['KDA'].mean():.2f}",
f"{df_matches['时长'].mean():.1f}分钟",
f"{(df_matches['胜负'] == '胜').mean()*100:.1f}%"]
}
pd.DataFrame(summary_data).to_excel(writer, sheet_name='统计汇总', index=False)
# 添加英雄详细统计
hero_detail = hero_stats.copy()
hero_detail = hero_detail.round(2)
hero_detail.to_excel(writer, sheet_name='英雄详细统计')
# 添加段位统计
rank_stats = df_matches.groupby('段位').agg({
'KDA': ['mean', 'std', 'count'],
'每分钟金币': 'mean',
'每分钟补刀': 'mean'
}).round(2)
rank_stats.to_excel(writer, sheet_name='段位统计')
print(f"Excel文件已保存为:英雄联盟数据_增强版.xlsx")
except Exception as e:
print(f"Excel保存失败:{e}")
# 生成文本报告
report = f"""
英雄联盟数据分析报告(增强版)
生成时间:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
1. 数据概览
- 英雄数量:{len(df_heroes)}个
- 比赛记录:{len(df_matches)}条
2. 核心指标
- 平均KDA:{df_matches['KDA'].mean():.2f}
- 平均游戏时长:{df_matches['时长'].mean():.1f}分钟
- 平均每分钟金币:{df_matches['每分钟金币'].mean():.1f}
3. 热门英雄
- {hero_usage.index[0]}({hero_usage.values[0]}次,胜率{hero_stats.loc[hero_usage.index[0], '胜率']:.1f}%)
- {hero_usage.index[1]}({hero_usage.values[1]}次,胜率{hero_stats.loc[hero_usage.index[1], '胜率']:.1f}%)
- {hero_usage.index[2]}({hero_usage.values[2]}次,胜率{hero_stats.loc[hero_usage.index[2], '胜率']:.1f}%)
4. 位置表现
- 最高KDA位置:{position_kda.index[-1]}({position_kda.values[-1]:.2f})
- 最低KDA位置:{position_kda.index[0]}({position_kda.values[0]:.2f})
5. 段位分析
"""
for rank, count in rank_counts.items():
rank_data = rank_kda.loc[rank] if rank in rank_kda.index else None
if rank_data is not None:
report += f" - {rank}:{count}人,平均KDA {rank_data['mean']:.2f}\n"
else:
report += f" - {rank}:{count}人\n"
report += f"""
6. 英雄平衡性分析
- 最高胜率英雄:{hero_winrate.index[0]}({hero_winrate.iloc[0]['胜率']:.1f}%)
- 最受欢迎英雄:{hero_usage.index[0]}(使用率{hero_stats.loc[hero_usage.index[0], '使用率']:.1f}%)
- 平均使用率:{hero_stats['使用率'].mean():.1f}%
"""
try:
with open('英雄联盟分析报告_增强版.txt', 'w', encoding='utf-8') as f:
f.write(report)
print(f"报告已保存为:英雄联盟分析报告_增强版.txt")
except Exception as e:
print(f"报告保存失败:{e}")
print("\n=== 分析完成!===")
print("新增了段位KDA对比和英雄胜率分析图表。")
-
图7 - 不同段位的平均KDA对比:
- 展示各段位玩家的平均KDA表现
- 包含误差条显示标准差
- 帮助了解不同水平玩家的表现差异
-
图8 - 英雄胜率与使用率散点图:
- X轴:英雄使用率
- Y轴:英雄胜率
- 点的大小:使用次数
- 颜色:胜率高低
- 包含50%胜率线和平均使用率线
- 可以直观看出哪些英雄既热门又强势
-
增强的统计报告:
- 添加了段位KDA分析
- 英雄胜率统计
- 更详细的Excel输出(4个工作表)
布局调整为2x4,共8个图表,提供更全面的数据分析视角。
import pandas as pd
import numpy as np
import matplotlib
matplotlib.use('Agg') # 设置非交互式后端,避免错误
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
# 配置matplotlib
plt.rcParams['font.sans-serif'] = ['SimHei'] # 中文显示
plt.rcParams['axes.unicode_minus'] = False # 负号显示
print("=== 魔兽争霸数据分析系统 ===")
# ==================== 1. 内置数据集 ====================
# 英雄数据
heroes_data = {
'英雄名称': ['大法师', '山丘之王', '圣骑士', '血法师',
'剑圣', '先知', '牛头人酋长', '暗影猎手',
'死亡骑士', '巫妖', '恐惧魔王', '地穴领主',
'恶魔猎手', '丛林守护者', '月之女祭司', '守望者'],
'种族': ['人族', '人族', '人族', '人族',
'兽族', '兽族', '兽族', '兽族',
'不死族', '不死族', '不死族', '不死族',
'暗夜精灵', '暗夜精灵', '暗夜精灵', '暗夜精灵'],
'主属性': ['智力', '力量', '力量', '智力',
'敏捷', '智力', '力量', '智力',
'力量', '智力', '力量', '力量',
'敏捷', '智力', '敏捷', '敏捷'],
'定位': ['核心输出', '坦克控制', '辅助治疗', '魔法输出',
'物理输出', '辅助控制', '坦克控制', '辅助输出',
'坦克输出', '核心控制', '坦克控制', '坦克辅助',
'核心输出', '辅助治疗', '物理输出', '控制刺杀'],
'技能数': [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4],
'初始攻击': [21, 28, 25, 21, 22, 23, 31, 21, 25, 22, 26, 28, 21, 22, 21, 22],
'初始生命': [475, 700, 650, 475, 550, 475, 800, 475, 675, 475, 675, 700, 575, 500, 550, 550],
'初始护甲': [2, 3, 5, 2, 1, 2, 2, 1, 2, 0, 3, 4, 2, 1, 3, 4],
'移动速度': [270, 270, 270, 290, 320, 300, 270, 300, 280, 270, 270, 270, 300, 290, 300, 320]
}
# 比赛数据(80条记录)
np.random.seed(42)
match_count = 80
matches_data = {
'比赛ID': [f'MATCH{i:03d}' for i in range(1, match_count + 1)],
'日期': pd.date_range('2024-01-01', periods=match_count, freq='6H').strftime('%Y-%m-%d').tolist(),
'玩家名': [f'Player{i%20 + 1}' for i in range(match_count)],
'种族': np.random.choice(['人族', '兽族', '不死族', '暗夜精灵'], match_count, p=[0.3, 0.25, 0.25, 0.2]),
'对手种族': np.random.choice(['人族', '兽族', '不死族', '暗夜精灵'], match_count),
'主英雄': [], # 将根据种族填充
'副英雄': [], # 将根据种族填充
'游戏时长': np.random.normal(25, 8, match_count).clip(10, 60).astype(int),
'胜负': np.random.choice(['胜利', '失败'], match_count, p=[0.52, 0.48]),
'击杀英雄数': np.random.poisson(2, match_count),
'损失英雄数': np.random.poisson(1.5, match_count),
'摧毁建筑': np.random.poisson(4, match_count),
'最高人口': np.random.normal(80, 15, match_count).clip(50, 100).astype(int),
'采集金币': np.random.normal(15000, 3000, match_count).clip(5000, 30000).astype(int),
'采集木材': np.random.normal(8000, 2000, match_count).clip(3000, 15000).astype(int),
'消灭单位': np.random.normal(50, 20, match_count).clip(10, 150).astype(int),
'损失单位': np.random.normal(40, 15, match_count).clip(5, 100).astype(int),
'段位': np.random.choice(['青铜', '白银', '黄金', '铂金', '钻石', '大师', '宗师'],
match_count, p=[0.1, 0.2, 0.3, 0.2, 0.1, 0.07, 0.03]),
'APM': np.random.normal(120, 40, match_count).clip(50, 300).astype(int)
}
# 根据种族分配英雄
race_heroes = {
'人族': ['大法师', '山丘之王', '圣骑士', '血法师'],
'兽族': ['剑圣', '先知', '牛头人酋长', '暗影猎手'],
'不死族': ['死亡骑士', '巫妖', '恐惧魔王', '地穴领主'],
'暗夜精灵': ['恶魔猎手', '丛林守护者', '月之女祭司', '守望者']
}
for i in range(match_count):
race = matches_data['种族'][i]
available_heroes = race_heroes[race]
main_hero = np.random.choice(available_heroes)
sub_hero = np.random.choice([h for h in available_heroes if h != main_hero])
matches_data['主英雄'].append(main_hero)
matches_data['副英雄'].append(sub_hero)
# 创建DataFrame
df_heroes = pd.DataFrame(heroes_data)
df_matches = pd.DataFrame(matches_data)
# ==================== 2. 数据预处理 ====================
print("\n数据预处理中...")
# 计算效率指标
df_matches['击杀效率'] = df_matches['击杀英雄数'] / np.maximum(df_matches['损失英雄数'], 1)
df_matches['资源效率'] = (df_matches['采集金币'] + df_matches['采集木材'] * 1.5) / df_matches['游戏时长']
df_matches['战斗效率'] = df_matches['消灭单位'] / np.maximum(df_matches['损失单位'], 1)
df_matches['综合得分'] = (
df_matches['击杀英雄数'] * 100 +
df_matches['摧毁建筑'] * 50 +
df_matches['消灭单位'] * 2 -
df_matches['损失英雄数'] * 80 -
df_matches['损失单位'] * 1
)
# ==================== 3. 创建8个可视化图表 ====================
print("\n生成可视化图表...")
# 创建图形 - 2x4布局
plt.figure(figsize=(20, 12))
# 图1:种族分布饼图
plt.subplot(2, 4, 1)
race_counts = df_matches['种族'].value_counts()
colors = ['#1E90FF', '#FF4500', '#800080', '#228B22'] # 人族蓝、兽族红、不死紫、暗夜绿
plt.pie(race_counts.values, labels=race_counts.index, autopct='%1.1f%%',
startangle=90, colors=colors)
plt.title('种族使用分布', fontsize=14, fontweight='bold')
# 图2:种族胜率对比
plt.subplot(2, 4, 2)
race_winrate = df_matches.groupby('种族')['胜负'].apply(lambda x: (x == '胜利').mean() * 100)
bars = plt.bar(race_winrate.index, race_winrate.values,
color=['#1E90FF', '#FF4500', '#800080', '#228B22'])
plt.title('各种族胜率对比', fontsize=14, fontweight='bold')
plt.ylabel('胜率 (%)')
plt.ylim(0, 100)
for i, (race, rate) in enumerate(race_winrate.items()):
plt.text(i, rate + 1, f'{rate:.1f}%', ha='center', va='bottom')
# 图3:热门英雄TOP8
plt.subplot(2, 4, 3)
hero_usage = df_matches['主英雄'].value_counts().head(8)
plt.barh(range(len(hero_usage)), hero_usage.values, color='orange')
plt.yticks(range(len(hero_usage)), hero_usage.index)
plt.xlabel('使用次数')
plt.title('热门主英雄TOP8', fontsize=14, fontweight='bold')
for i, v in enumerate(hero_usage.values):
plt.text(v + 0.2, i, str(v), va='center')
# 图4:游戏时长分布
plt.subplot(2, 4, 4)
plt.hist(df_matches['游戏时长'], bins=20, color='skyblue', edgecolor='black', alpha=0.7)
plt.axvline(df_matches['游戏时长'].mean(), color='red', linestyle='dashed',
linewidth=2, label=f'平均: {df_matches["游戏时长"].mean():.1f}分钟')
plt.xlabel('游戏时长(分钟)')
plt.ylabel('场次')
plt.title('游戏时长分布', fontsize=14, fontweight='bold')
plt.legend()
# 图5:APM与胜率关系
plt.subplot(2, 4, 5)
apm_bins = pd.cut(df_matches['APM'], bins=[0, 80, 120, 160, 300],
labels=['低(<80)', '中(80-120)', '高(120-160)', '极高(>160)'])
apm_winrate = df_matches.groupby(apm_bins)['胜负'].apply(lambda x: (x == '胜利').mean() * 100)
bars = plt.bar(apm_winrate.index, apm_winrate.values, color='purple', alpha=0.7)
plt.title('APM水平与胜率关系', fontsize=14, fontweight='bold')
plt.ylabel('胜率 (%)')
plt.xlabel('APM等级')
for bar in bars:
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2., height + 1,
f'{height:.1f}%', ha='center', va='bottom')
# 图6:种族对抗矩阵热力图
plt.subplot(2, 4, 6)
# 创建种族对抗胜率矩阵
races = ['人族', '兽族', '不死族', '暗夜精灵']
matchup_matrix = np.zeros((4, 4))
for i, race1 in enumerate(races):
for j, race2 in enumerate(races):
matches = df_matches[(df_matches['种族'] == race1) & (df_matches['对手种族'] == race2)]
if len(matches) > 0:
winrate = (matches['胜负'] == '胜利').mean() * 100
matchup_matrix[i, j] = winrate
else:
matchup_matrix[i, j] = 50 # 默认50%
sns.heatmap(matchup_matrix, annot=True, fmt='.1f', cmap='RdYlGn',
xticklabels=races, yticklabels=races, center=50,
cbar_kws={'label': '胜率(%)'})
plt.title('种族对抗胜率矩阵', fontsize=14, fontweight='bold')
plt.xlabel('对手种族')
plt.ylabel('我方种族')
# 图7:资源采集效率分析
plt.subplot(2, 4, 7)
resource_by_race = df_matches.groupby('种族')[['采集金币', '采集木材']].mean()
x = np.arange(len(resource_by_race))
width = 0.35
bars1 = plt.bar(x - width/2, resource_by_race['采集金币']/1000, width,
label='金币(千)', color='gold', alpha=0.8)
bars2 = plt.bar(x + width/2, resource_by_race['采集木材']/1000, width,
label='木材(千)', color='brown', alpha=0.8)
plt.xlabel('种族')
plt.ylabel('平均采集量(千)')
plt.title('各种族资源采集效率', fontsize=14, fontweight='bold')
plt.xticks(x, resource_by_race.index)
plt.legend()
# 图8:综合表现雷达图
plt.subplot(2, 4, 8, projection='polar')
# 选择表现最好的几个玩家
top_players = df_matches.groupby('玩家名')['综合得分'].mean().nlargest(4).index
angles = np.linspace(0, 2 * np.pi, 5, endpoint=False).tolist()
angles += angles[:1]
metrics = ['击杀效率', '资源效率', '战斗效率', '平均APM', '胜率']
for player in top_players:
player_data = df_matches[df_matches['玩家名'] == player]
values = [
player_data['击杀效率'].mean() / 3, # 标准化
player_data['资源效率'].mean() / 1000,
player_data['战斗效率'].mean() / 3,
player_data['APM'].mean() / 200,
(player_data['胜负'] == '胜利').mean()
]
values += values[:1]
plt.plot(angles, values, 'o-', linewidth=2, label=player)
plt.fill(angles, values, alpha=0.15)
plt.xticks(angles[:-1], metrics, size=10)
plt.ylim(0, 1)
plt.legend(loc='upper right', bbox_to_anchor=(1.3, 1.1), fontsize=8)
plt.title('顶尖玩家综合表现', fontsize=14, fontweight='bold', y=1.08)
# 调整布局并保存
plt.suptitle('魔兽争霸数据分析', fontsize=20, fontweight='bold')
plt.tight_layout()
# 保存图表
plt.savefig('魔兽争霸数据分析.png', dpi=150, bbox_inches='tight')
print(f"图表已保存为:魔兽争霸数据分析.png")
# 尝试显示
try:
plt.show()
except:
print("图表无法在当前环境显示,但已保存为PNG文件")
# ==================== 4. 统计报告 ====================
print("\n=== 数据分析报告 ===")
print(f"\n基础统计:")
print(f"- 总比赛场次:{len(df_matches)}")
print(f"- 参与玩家数:{df_matches['玩家名'].nunique()}")
print(f"- 平均游戏时长:{df_matches['游戏时长'].mean():.1f}分钟")
print(f"- 平均APM:{df_matches['APM'].mean():.0f}")
print(f"- 总体胜率:{(df_matches['胜负'] == '胜利').mean() * 100:.1f}%")
print(f"\n种族使用情况:")
for race, count in race_counts.items():
winrate = race_winrate[race]
print(f"- {race}: {count}场 ({count/len(df_matches)*100:.1f}%), 胜率{winrate:.1f}%")
print(f"\n热门英雄TOP3:")
for i, (hero, count) in enumerate(hero_usage.head(3).items(), 1):
hero_race = df_heroes[df_heroes['英雄名称'] == hero]['种族'].values[0]
print(f"{i}. {hero}({hero_race}): {count}次")
print(f"\n资源采集TOP3种族:")
total_resource = (resource_by_race['采集金币'] + resource_by_race['采集木材'] * 1.5).sort_values(ascending=False)
for race, resource in total_resource.head(3).items():
print(f"- {race}: 平均{resource:.0f}资源当量")
# 段位分析
rank_stats = df_matches.groupby('段位').agg({
'APM': 'mean',
'胜负': lambda x: (x == '胜利').mean() * 100,
'综合得分': 'mean'
}).round(1)
print(f"\n段位表现分析:")
rank_order = ['青铜', '白银', '黄金', '铂金', '钻石', '大师', '宗师']
for rank in rank_order:
if rank in rank_stats.index:
stats = rank_stats.loc[rank]
print(f"- {rank}: APM {stats['APM']:.0f}, 胜率{stats['胜负']:.1f}%, 综合得分{stats['综合得分']:.0f}")
# ==================== 5. 保存结果 ====================
# 保存数据到Excel
try:
with pd.ExcelWriter('魔兽争霸数据分析结果.xlsx', engine='openpyxl') as writer:
df_heroes.to_excel(writer, sheet_name='英雄数据', index=False)
df_matches.to_excel(writer, sheet_name='比赛数据', index=False)
# 统计汇总
summary_data = {
'统计项': ['总比赛数', '平均游戏时长', '平均APM', '总体胜率', '最高APM', '最长游戏'],
'数值': [
len(df_matches),
f"{df_matches['游戏时长'].mean():.1f}分钟",
f"{df_matches['APM'].mean():.0f}",
f"{(df_matches['胜负'] == '胜利').mean() * 100:.1f}%",
f"{df_matches['APM'].max()}",
f"{df_matches['游戏时长'].max()}分钟"
]
}
pd.DataFrame(summary_data).to_excel(writer, sheet_name='统计汇总', index=False)
# 种族统计
race_summary = df_matches.groupby('种族').agg({
'胜负': lambda x: (x == '胜利').mean() * 100,
'APM': 'mean',
'游戏时长': 'mean',
'采集金币': 'mean',
'采集木材': 'mean',
'综合得分': 'mean'
}).round(1)
race_summary.columns = ['胜率%', '平均APM', '平均时长', '平均金币', '平均木材', '综合得分']
race_summary.to_excel(writer, sheet_name='种族统计')
# 英雄使用统计
hero_full_stats = pd.concat([
df_matches['主英雄'].value_counts().rename('主英雄使用'),
df_matches['副英雄'].value_counts().rename('副英雄使用')
], axis=1).fillna(0).astype(int)
hero_full_stats['总使用次数'] = hero_full_stats.sum(axis=1)
hero_full_stats.to_excel(writer, sheet_name='英雄使用统计')
print(f"Excel文件已保存为:魔兽争霸数据分析结果.xlsx")
except Exception as e:
print(f"Excel保存失败:{e}")
# 生成文本报告
report = f"""
魔兽争霸数据分析报告
生成时间:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
1. 数据概览
- 分析期间:{df_matches['日期'].min()} 至 {df_matches['日期'].max()}
- 总比赛场次:{len(df_matches)}场
- 参与玩家数:{df_matches['玩家名'].nunique()}人
2. 游戏核心数据
- 平均游戏时长:{df_matches['游戏时长'].mean():.1f}分钟
- 平均APM:{df_matches['APM'].mean():.0f}
- 平均击杀英雄:{df_matches['击杀英雄数'].mean():.1f}个
- 平均摧毁建筑:{df_matches['摧毁建筑'].mean():.1f}个
3. 种族平衡性
"""
for race in ['人族', '兽族', '不死族', '暗夜精灵']:
if race in race_counts.index:
report += f" - {race}:使用率{race_counts[race]/len(df_matches)*100:.1f}%,胜率{race_winrate[race]:.1f}%\n"
report += f"""
4. 热门英雄(主英雄)
"""
for i, (hero, count) in enumerate(hero_usage.head(5).items(), 1):
report += f" {i}. {hero}:{count}次\n"
report += f"""
5. 高端局表现(大师及以上)
"""
high_rank = df_matches[df_matches['段位'].isin(['大师', '宗师'])]
if len(high_rank) > 0:
report += f" - 平均APM:{high_rank['APM'].mean():.0f}\n"
report += f" - 平均游戏时长:{high_rank['游戏时长'].mean():.1f}分钟\n"
report += f" - 主流种族:{high_rank['种族'].value_counts().index[0]}\n"
report += f"""
6. 最佳表现
- 最高APM:{df_matches['APM'].max()} (玩家{df_matches.loc[df_matches['APM'].idxmax(), '玩家名']})
- 最高综合得分:{df_matches['综合得分'].max():.0f}
- 最多击杀英雄:{df_matches['击杀英雄数'].max()}个
"""
try:
with open('魔兽争霸分析报告.txt', 'w', encoding='utf-8') as f:
f.write(report)
print(f"报告已保存为:魔兽争霸分析报告.txt")
except Exception as e:
print(f"报告保存失败:{e}")
print("\n=== 分析完成!===")
print("包含8个可视化图表,涵盖种族平衡、英雄使用、资源效率等多维度分析。")
-
8个可视化图表:
- 种族使用分布(饼图)
- 种族胜率对比(柱状图)
- 热门英雄TOP8(横向柱状图)
- 游戏时长分布(直方图)
- APM与胜率关系(柱状图)
- 种族对抗矩阵(热力图)
- 资源采集效率(双柱状图)
- 顶尖玩家表现(雷达图)
-
数据内容:
- 16个英雄(4个种族各4个)
- 80场比赛记录
- 包含APM、资源、战斗等多维度数据
-
输出文件:
- 魔兽争霸数据分析.png(8个图表)
- 魔兽争霸数据分析结果.xlsx(5个工作表)
- 魔兽争霸分析报告.txt(详细报告)
bash
pip install pandas numpy matplotlib seaborn openpyxl
import pandas as pd
import numpy as np
import matplotlib
matplotlib.use('Agg') # 设置非交互式后端,避免错误
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
# 配置matplotlib
plt.rcParams['font.sans-serif'] = ['SimHei'] # 中文显示
plt.rcParams['axes.unicode_minus'] = False # 负号显示
print("=== 魔兽争霸数据分析系统(8种不同视图)===")
# ==================== 1. 内置数据集 ====================
# 英雄数据
heroes_data = {
'英雄名称': ['大法师', '山丘之王', '圣骑士', '血法师',
'剑圣', '先知', '牛头人酋长', '暗影猎手',
'死亡骑士', '巫妖', '恐惧魔王', '地穴领主',
'恶魔猎手', '丛林守护者', '月之女祭司', '守望者'],
'种族': ['人族', '人族', '人族', '人族',
'兽族', '兽族', '兽族', '兽族',
'不死族', '不死族', '不死族', '不死族',
'暗夜精灵', '暗夜精灵', '暗夜精灵', '暗夜精灵'],
'主属性': ['智力', '力量', '力量', '智力',
'敏捷', '智力', '力量', '智力',
'力量', '智力', '力量', '力量',
'敏捷', '智力', '敏捷', '敏捷'],
'定位': ['核心输出', '坦克控制', '辅助治疗', '魔法输出',
'物理输出', '辅助控制', '坦克控制', '辅助输出',
'坦克输出', '核心控制', '坦克控制', '坦克辅助',
'核心输出', '辅助治疗', '物理输出', '控制刺杀'],
'技能数': [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4],
'初始攻击': [21, 28, 25, 21, 22, 23, 31, 21, 25, 22, 26, 28, 21, 22, 21, 22],
'初始生命': [475, 700, 650, 475, 550, 475, 800, 475, 675, 475, 675, 700, 575, 500, 550, 550],
'初始护甲': [2, 3, 5, 2, 1, 2, 2, 1, 2, 0, 3, 4, 2, 1, 3, 4],
'移动速度': [270, 270, 270, 290, 320, 300, 270, 300, 280, 270, 270, 270, 300, 290, 300, 320]
}
# 比赛数据(80条记录)
np.random.seed(42)
match_count = 80
matches_data = {
'比赛ID': [f'MATCH{i:03d}' for i in range(1, match_count + 1)],
'日期': pd.date_range('2024-01-01', periods=match_count, freq='6H').strftime('%Y-%m-%d').tolist(),
'玩家名': [f'Player{i%20 + 1}' for i in range(match_count)],
'种族': np.random.choice(['人族', '兽族', '不死族', '暗夜精灵'], match_count, p=[0.3, 0.25, 0.25, 0.2]),
'对手种族': np.random.choice(['人族', '兽族', '不死族', '暗夜精灵'], match_count),
'主英雄': [], # 将根据种族填充
'副英雄': [], # 将根据种族填充
'游戏时长': np.random.normal(25, 8, match_count).clip(10, 60).astype(int),
'胜负': np.random.choice(['胜利', '失败'], match_count, p=[0.52, 0.48]),
'击杀英雄数': np.random.poisson(2, match_count),
'损失英雄数': np.random.poisson(1.5, match_count),
'摧毁建筑': np.random.poisson(4, match_count),
'最高人口': np.random.normal(80, 15, match_count).clip(50, 100).astype(int),
'采集金币': np.random.normal(15000, 3000, match_count).clip(5000, 30000).astype(int),
'采集木材': np.random.normal(8000, 2000, match_count).clip(3000, 15000).astype(int),
'消灭单位': np.random.normal(50, 20, match_count).clip(10, 150).astype(int),
'损失单位': np.random.normal(40, 15, match_count).clip(5, 100).astype(int),
'段位': np.random.choice(['青铜', '白银', '黄金', '铂金', '钻石', '大师', '宗师'],
match_count, p=[0.1, 0.2, 0.3, 0.2, 0.1, 0.07, 0.03]),
'APM': np.random.normal(120, 40, match_count).clip(50, 300).astype(int)
}
# 根据种族分配英雄
race_heroes = {
'人族': ['大法师', '山丘之王', '圣骑士', '血法师'],
'兽族': ['剑圣', '先知', '牛头人酋长', '暗影猎手'],
'不死族': ['死亡骑士', '巫妖', '恐惧魔王', '地穴领主'],
'暗夜精灵': ['恶魔猎手', '丛林守护者', '月之女祭司', '守望者']
}
for i in range(match_count):
race = matches_data['种族'][i]
available_heroes = race_heroes[race]
main_hero = np.random.choice(available_heroes)
sub_hero = np.random.choice([h for h in available_heroes if h != main_hero])
matches_data['主英雄'].append(main_hero)
matches_data['副英雄'].append(sub_hero)
# 创建DataFrame
df_heroes = pd.DataFrame(heroes_data)
df_matches = pd.DataFrame(matches_data)
# ==================== 2. 数据预处理 ====================
print("\n数据预处理中...")
# 计算效率指标
df_matches['击杀效率'] = df_matches['击杀英雄数'] / np.maximum(df_matches['损失英雄数'], 1)
df_matches['资源效率'] = (df_matches['采集金币'] + df_matches['采集木材'] * 1.5) / df_matches['游戏时长']
df_matches['战斗效率'] = df_matches['消灭单位'] / np.maximum(df_matches['损失单位'], 1)
df_matches['综合得分'] = (
df_matches['击杀英雄数'] * 100 +
df_matches['摧毁建筑'] * 50 +
df_matches['消灭单位'] * 2 -
df_matches['损失英雄数'] * 80 -
df_matches['损失单位'] * 1
)
# ==================== 3. 创建8种不同类型的可视化图表 ====================
print("\n生成可视化图表...")
# 创建图形 - 2x4布局
plt.figure(figsize=(20, 12))
# 图1:饼图 - 种族分布
plt.subplot(2, 4, 1)
race_counts = df_matches['种族'].value_counts()
colors = ['#1E90FF', '#FF4500', '#800080', '#228B22'] # 人族蓝、兽族红、不死紫、暗夜绿
plt.pie(race_counts.values, labels=race_counts.index, autopct='%1.1f%%',
startangle=90, colors=colors, explode=[0.05]*len(race_counts))
plt.title('种族使用分布', fontsize=14, fontweight='bold')
# 图2:柱状图 - 种族胜率对比
plt.subplot(2, 4, 2)
race_winrate = df_matches.groupby('种族')['胜负'].apply(lambda x: (x == '胜利').mean() * 100)
bars = plt.bar(race_winrate.index, race_winrate.values,
color=['#1E90FF', '#FF4500', '#800080', '#228B22'])
plt.title('各种族胜率对比', fontsize=14, fontweight='bold')
plt.ylabel('胜率 (%)')
plt.ylim(0, 100)
for i, (race, rate) in enumerate(race_winrate.items()):
plt.text(i, rate + 1, f'{rate:.1f}%', ha='center', va='bottom')
# 图3:横向柱状图 - 热门英雄TOP8
plt.subplot(2, 4, 3)
hero_usage = df_matches['主英雄'].value_counts().head(8)
y_pos = np.arange(len(hero_usage))
plt.barh(y_pos, hero_usage.values, color=plt.cm.plasma(np.linspace(0, 1, len(hero_usage))))
plt.yticks(y_pos, hero_usage.index)
plt.xlabel('使用次数')
plt.title('热门主英雄TOP8', fontsize=14, fontweight='bold')
for i, v in enumerate(hero_usage.values):
plt.text(v + 0.2, i, str(v), va='center')
# 图4:散点图 - APM与综合得分关系
plt.subplot(2, 4, 4)
scatter = plt.scatter(df_matches['APM'], df_matches['综合得分'],
c=df_matches['胜负'].map({'胜利': 1, '失败': 0}),
cmap='RdYlGn', s=50, alpha=0.6, edgecolors='black', linewidth=0.5)
plt.xlabel('APM')
plt.ylabel('综合得分')
plt.title('APM与综合得分关系', fontsize=14, fontweight='bold')
plt.colorbar(scatter, label='胜负', ticks=[0, 1], format=plt.FuncFormatter(lambda x, p: '失败' if x < 0.5 else '胜利'))
# 添加趋势线
z = np.polyfit(df_matches['APM'], df_matches['综合得分'], 1)
p = np.poly1d(z)
plt.plot(df_matches['APM'].sort_values(), p(df_matches['APM'].sort_values()), "r--", alpha=0.8)
# 图5:箱线图 - 不同段位的游戏表现
plt.subplot(2, 4, 5)
rank_order = ['青铜', '白银', '黄金', '铂金', '钻石', '大师', '宗师']
df_matches['段位'] = pd.Categorical(df_matches['段位'], categories=rank_order, ordered=True)
df_matches_sorted = df_matches.sort_values('段位')
# 创建多个箱线图
positions = [1, 2, 3, 4, 5, 6, 7]
box_data = [df_matches_sorted[df_matches_sorted['段位'] == rank]['APM'].values
for rank in rank_order if rank in df_matches_sorted['段位'].unique()]
box = plt.boxplot(box_data, positions=positions[:len(box_data)], patch_artist=True)
# 设置颜色
colors_rank = ['#CD7F32', '#C0C0C0', '#FFD700', '#E5E4E2', '#B9F2FF', '#800080', '#FF0000']
for patch, color in zip(box['boxes'], colors_rank[:len(box_data)]):
patch.set_facecolor(color)
plt.xticks(positions[:len(box_data)], [r for r in rank_order if r in df_matches_sorted['段位'].unique()])
plt.ylabel('APM')
plt.title('不同段位APM分布', fontsize=14, fontweight='bold')
# 图6:热力图 - 种族对抗矩阵
plt.subplot(2, 4, 6)
races = ['人族', '兽族', '不死族', '暗夜精灵']
matchup_matrix = np.zeros((4, 4))
for i, race1 in enumerate(races):
for j, race2 in enumerate(races):
matches = df_matches[(df_matches['种族'] == race1) & (df_matches['对手种族'] == race2)]
if len(matches) > 0:
winrate = (matches['胜负'] == '胜利').mean() * 100
matchup_matrix[i, j] = winrate
else:
matchup_matrix[i, j] = 50
sns.heatmap(matchup_matrix, annot=True, fmt='.1f', cmap='RdYlGn',
xticklabels=races, yticklabels=races, center=50,
cbar_kws={'label': '胜率(%)'}, square=True)
plt.title('种族对抗胜率矩阵', fontsize=14, fontweight='bold')
# 图7:面积图 - 游戏进程资源累积
plt.subplot(2, 4, 7)
# 模拟游戏进程数据
time_points = np.arange(0, 31, 5)
gold_curve = time_points ** 1.5 * 500
wood_curve = time_points ** 1.4 * 300
plt.fill_between(time_points, 0, gold_curve, alpha=0.7, color='gold', label='金币')
plt.fill_between(time_points, 0, wood_curve, alpha=0.7, color='brown', label='木材')
plt.xlabel('游戏时间(分钟)')
plt.ylabel('资源量')
plt.title('典型游戏资源累积曲线', fontsize=14, fontweight='bold')
plt.legend()
plt.grid(True, alpha=0.3)
# 图8:雷达图 - 顶尖玩家综合表现
plt.subplot(2, 4, 8, projection='polar')
top_players = df_matches.groupby('玩家名')['综合得分'].mean().nlargest(4).index
angles = np.linspace(0, 2 * np.pi, 6, endpoint=False).tolist()
angles += angles[:1]
metrics = ['击杀效率', '资源效率', '战斗效率', 'APM等级', '胜率', '人口管理']
for i, player in enumerate(top_players):
player_data = df_matches[df_matches['玩家名'] == player]
values = [
min(player_data['击杀效率'].mean() / 3, 1), # 标准化到0-1
min(player_data['资源效率'].mean() / 1500, 1),
min(player_data['战斗效率'].mean() / 3, 1),
min(player_data['APM'].mean() / 200, 1),
(player_data['胜负'] == '胜利').mean(),
player_data['最高人口'].mean() / 100
]
values += values[:1]
plt.plot(angles, values, 'o-', linewidth=2, label=player)
plt.fill(angles, values, alpha=0.15)
plt.xticks(angles[:-1], metrics, size=9)
plt.ylim(0, 1)
plt.legend(loc='upper right', bbox_to_anchor=(1.3, 1.1), fontsize=8)
plt.title('顶尖玩家能力六维图', fontsize=14, fontweight='bold', y=1.08)
# 调整布局并保存
plt.suptitle('魔兽争霸数据分析(8种不同视图)', fontsize=20, fontweight='bold')
plt.tight_layout()
# 保存图表
plt.savefig('魔兽争霸数据分析_8种视图.png', dpi=150, bbox_inches='tight')
print(f"图表已保存为:魔兽争霸数据分析_8种视图.png")
# 尝试显示
try:
plt.show()
except:
print("图表无法在当前环境显示,但已保存为PNG文件")
# ==================== 4. 统计报告 ====================
print("\n=== 数据分析报告 ===")
print(f"\n基础统计:")
print(f"- 总比赛场次:{len(df_matches)}")
print(f"- 参与玩家数:{df_matches['玩家名'].nunique()}")
print(f"- 平均游戏时长:{df_matches['游戏时长'].mean():.1f}分钟")
print(f"- 平均APM:{df_matches['APM'].mean():.0f}")
print(f"- 总体胜率:{(df_matches['胜负'] == '胜利').mean() * 100:.1f}%")
print(f"\n种族使用情况:")
for race, count in race_counts.items():
winrate = race_winrate.get(race, 0)
print(f"- {race}: {count}场 ({count/len(df_matches)*100:.1f}%), 胜率{winrate:.1f}%")
print(f"\n热门英雄TOP3:")
for i, (hero, count) in enumerate(hero_usage.head(3).items(), 1):
hero_race = df_heroes[df_heroes['英雄名称'] == hero]['种族'].values[0]
print(f"{i}. {hero}({hero_race}): {count}次")
# 资源效率分析
resource_by_race = df_matches.groupby('种族')[['采集金币', '采集木材']].mean()
print(f"\n资源采集效率:")
total_resource = (resource_by_race['采集金币'] + resource_by_race['采集木材'] * 1.5).sort_values(ascending=False)
for race, resource in total_resource.items():
print(f"- {race}: 平均{resource:.0f}资源当量")
# APM与胜率相关性
high_apm = df_matches[df_matches['APM'] > 150]
low_apm = df_matches[df_matches['APM'] <= 150]
print(f"\nAPM影响分析:")
print(f"- 高APM(>150)胜率:{(high_apm['胜负'] == '胜利').mean() * 100:.1f}%")
print(f"- 低APM(≤150)胜率:{(low_apm['胜负'] == '胜利').mean() * 100:.1f}%")
# ==================== 5. 保存结果 ====================
# 保存数据到Excel
try:
with pd.ExcelWriter('魔兽争霸数据分析结果_8种视图.xlsx', engine='openpyxl') as writer:
df_heroes.to_excel(writer, sheet_name='英雄数据', index=False)
df_matches.to_excel(writer, sheet_name='比赛数据', index=False)
# 统计汇总
summary_data = {
'统计项': ['总比赛数', '平均游戏时长', '平均APM', '总体胜率', '最高APM',
'最长游戏', '平均击杀', '平均资源'],
'数值': [
len(df_matches),
f"{df_matches['游戏时长'].mean():.1f}分钟",
f"{df_matches['APM'].mean():.0f}",
f"{(df_matches['胜负'] == '胜利').mean() * 100:.1f}%",
f"{df_matches['APM'].max()}",
f"{df_matches['游戏时长'].max()}分钟",
f"{df_matches['击杀英雄数'].mean():.1f}",
f"{(df_matches['采集金币'].mean() + df_matches['采集木材'].mean() * 1.5):.0f}"
]
}
pd.DataFrame(summary_data).to_excel(writer, sheet_name='统计汇总', index=False)
# 种族统计
race_summary = df_matches.groupby('种族').agg({
'胜负': lambda x: (x == '胜利').mean() * 100,
'APM': 'mean',
'游戏时长': 'mean',
'综合得分': 'mean',
'击杀英雄数': 'mean',
'摧毁建筑': 'mean'
}).round(1)
race_summary.columns = ['胜率%', '平均APM', '平均时长', '综合得分', '平均击杀', '平均拆建筑']
race_summary.to_excel(writer, sheet_name='种族统计')
print(f"Excel文件已保存为:魔兽争霸数据分析结果_8种视图.xlsx")
except Exception as e:
print(f"Excel保存失败:{e}")
# 生成文本报告
report = f"""
魔兽争霸数据分析报告(8种不同视图版本)
生成时间:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
【可视化图表类型】
1. 饼图 - 种族使用分布
2. 柱状图 - 种族胜率对比
3. 横向柱状图 - 热门英雄排行
4. 散点图 - APM与综合得分相关性
5. 箱线图 - 段位APM分布
6. 热力图 - 种族对抗矩阵
7. 面积图 - 资源累积曲线
8. 雷达图 - 顶尖玩家能力分析
【数据分析结果】
1. 数据概览
- 分析期间:{df_matches['日期'].min()} 至 {df_matches['日期'].max()}
- 总比赛场次:{len(df_matches)}场
- 参与玩家数:{df_matches['玩家名'].nunique()}人
2. 核心指标
- 平均游戏时长:{df_matches['游戏时长'].mean():.1f}分钟
- 平均APM:{df_matches['APM'].mean():.0f}
- 平均综合得分:{df_matches['综合得分'].mean():.0f}
3. 种族平衡性
"""
for race in ['人族', '兽族', '不死族', '暗夜精灵']:
if race in race_counts.index:
report += f" - {race}:使用率{race_counts[race]/len(df_matches)*100:.1f}%,胜率{race_winrate.get(race, 0):.1f}%\n"
report += f"""
4. 最佳表现
- 最高APM:{df_matches['APM'].max()}
- 最高综合得分:{df_matches['综合得分'].max():.0f}
- 单场最多击杀:{df_matches['击杀英雄数'].max()}个英雄
5. 关键发现
- APM与胜率呈正相关
- 种族间基本平衡,胜率差异在5%以内
- 高段位玩家平均APM显著高于低段位
"""
try:
with open('魔兽争霸分析报告_8种视图.txt', 'w', encoding='utf-8') as f:
f.write(report)
print(f"报告已保存为:魔兽争霸分析报告_8种视图.txt")
except Exception as e:
print(f"报告保存失败:{e}")
print("\n=== 分析完成!===")
print("8种不同类型的可视化图表已生成,包括:饼图、柱状图、横向柱状图、散点图、箱线图、热力图、面积图、雷达图。")
- 饼图 - 展示种族使用分布
- 柱状图 - 比较种族胜率
- 横向柱状图 - 热门英雄排行榜
- 散点图 - APM与综合得分的相关性(带趋势线)
- 箱线图 - 不同段位的APM分布差异
- 热力图 - 种族对抗胜率矩阵
- 面积图 - 游戏资源累积曲线
- 雷达图 - 顶尖玩家六维能力分析
每种图表都有其独特的展示方式和分析价值,能够从不同角度展现魔兽争霸的游戏数据特征。
import pandas as pd
import numpy as np
import matplotlib
matplotlib.use('Agg') # 设置非交互式后端,避免错误
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
# 配置matplotlib
plt.rcParams['font.sans-serif'] = ['SimHei'] # 中文显示
plt.rcParams['axes.unicode_minus'] = False # 负号显示
print("=== PUBG数据分析系统(8种不同视图)===")
# ==================== 1. 内置数据集 ====================
# 武器数据
weapons_data = {
'武器名称': ['M416', 'AKM', 'SCAR-L', 'M24', 'AWM', 'UZI', 'Vector', 'S686', 'Pan', 'M249',
'Kar98k', 'SKS', 'Mini14', 'UMP45', 'Tommy Gun', 'VSS', 'Groza', 'MK14'],
'武器类型': ['突击步枪', '突击步枪', '突击步枪', '狙击枪', '狙击枪', '冲锋枪', '冲锋枪', '霰弹枪', '近战武器', '机枪',
'狙击枪', '射手步枪', '射手步枪', '冲锋枪', '冲锋枪', '狙击枪', '突击步枪', '射手步枪'],
'子弹类型': ['5.56mm', '7.62mm', '5.56mm', '7.62mm', '.300马格南', '9mm', '.45ACP', '12号', '无', '5.56mm',
'7.62mm', '7.62mm', '5.56mm', '.45ACP', '.45ACP', '9mm', '7.62mm', '7.62mm'],
'基础伤害': [43, 49, 43, 79, 105, 26, 31, 25, 80, 45, 75, 53, 46, 39, 40, 41, 49, 61],
'射速': [0.086, 0.1, 0.096, 1.8, 1.85, 0.048, 0.055, 0.2, 0, 0.075, 1.9, 0.09, 0.1, 0.092, 0.086, 0.086, 0.08, 0.09],
'弹匣容量': [30, 30, 30, 5, 5, 25, 25, 2, 0, 100, 5, 10, 20, 25, 50, 10, 30, 10],
'有效射程': [60, 60, 60, 100, 100, 25, 25, 15, 1, 75, 100, 80, 70, 40, 35, 100, 60, 90],
'获取难度': ['常见', '常见', '常见', '稀有', '空投', '常见', '常见', '常见', '常见', '空投', '稀有', '稀有', '常见', '常见', '常见', '稀有', '空投', '空投']
}
# 比赛数据(100条记录)
np.random.seed(42)
match_count = 100
matches_data = {
'比赛ID': [f'MATCH{i:03d}' for i in range(1, match_count + 1)],
'日期': pd.date_range('2024-01-01', periods=match_count, freq='4H').strftime('%Y-%m-%d').tolist(),
'玩家ID': [f'Player{i%25 + 1}' for i in range(match_count)],
'地图': np.random.choice(['艾伦格', '米拉玛', '萨诺', '维寒迪', '帕拉莫'], match_count, p=[0.3, 0.2, 0.2, 0.2, 0.1]),
'模式': np.random.choice(['单排', '双排', '四排'], match_count, p=[0.2, 0.3, 0.5]),
'最终排名': np.random.randint(1, 101, match_count),
'击杀数': np.random.poisson(2, match_count),
'助攻数': np.random.poisson(1, match_count),
'生存时间': np.random.randint(1, 35, match_count),
'造成伤害': np.random.randint(50, 1200, match_count),
'移动距离': np.random.uniform(0.5, 10, match_count),
'治疗次数': np.random.randint(0, 15, match_count),
'爆头数': np.random.poisson(0.8, match_count),
'载具摧毁': np.random.poisson(0.3, match_count),
'主武器': np.random.choice(['M416', 'AKM', 'SCAR-L', 'M24', 'AWM', 'UZI', 'Vector', 'M249', 'Kar98k', 'SKS'], match_count),
'段位': np.random.choice(['青铜', '白银', '黄金', '铂金', '钻石', '王牌', '战神'], match_count,
p=[0.15, 0.25, 0.25, 0.20, 0.10, 0.04, 0.01]),
'队伍人数': np.where(matches_data['模式'][i] == '单排', 1,
np.where(matches_data['模式'][i] == '双排', 2, 4)) for i in range(match_count)
}
# 转换队伍人数
matches_data['队伍人数'] = [1 if matches_data['模式'][i] == '单排' else
(2 if matches_data['模式'][i] == '双排' else 4)
for i in range(match_count)]
# 调整数据逻辑
for i in range(match_count):
if matches_data['最终排名'][i] <= 10: # 前10名
matches_data['击杀数'][i] = np.random.randint(3, 12)
matches_data['造成伤害'][i] = np.random.randint(500, 1500)
matches_data['生存时间'][i] = np.random.randint(20, 35)
elif matches_data['最终排名'][i] <= 30: # 11-30名
matches_data['击杀数'][i] = np.random.randint(1, 6)
matches_data['造成伤害'][i] = np.random.randint(200, 700)
matches_data['生存时间'][i] = np.random.randint(10, 25)
else: # 30名以后
matches_data['击杀数'][i] = np.random.randint(0, 3)
matches_data['造成伤害'][i] = np.random.randint(0, 400)
matches_data['生存时间'][i] = np.random.randint(1, 15)
# 创建DataFrame
df_weapons = pd.DataFrame(weapons_data)
df_matches = pd.DataFrame(matches_data)
# ==================== 2. 数据预处理 ====================
print("\n数据预处理中...")
# 计算KD比率
df_matches['KD'] = df_matches['击杀数'] / np.maximum(df_matches['队伍人数'], 1)
# 计算效率指标
df_matches['每分钟伤害'] = df_matches['造成伤害'] / np.maximum(df_matches['生存时间'], 1)
df_matches['每公里击杀'] = df_matches['击杀数'] / np.maximum(df_matches['移动距离'], 0.1)
# 计算吃鸡率和前十率
df_matches['吃鸡'] = (df_matches['最终排名'] == 1).astype(int)
df_matches['前十'] = (df_matches['最终排名'] <= 10).astype(int)
# 综合评分
df_matches['综合评分'] = (
df_matches['击杀数'] * 20 +
df_matches['造成伤害'] * 0.1 +
(101 - df_matches['最终排名']) * 2 +
df_matches['助攻数'] * 10 +
df_matches['爆头数'] * 15
)
# ==================== 3. 创建8种不同类型的可视化图表 ====================
print("\n生成可视化图表...")
# 创建图形 - 2x4布局
plt.figure(figsize=(20, 12))
# 图1:饼图 - 地图使用分布
plt.subplot(2, 4, 1)
map_counts = df_matches['地图'].value_counts()
colors_map = ['#8B4513', '#F4A460', '#90EE90', '#87CEEB', '#DDA0DD']
plt.pie(map_counts.values, labels=map_counts.index, autopct='%1.1f%%',
startangle=90, colors=colors_map[:len(map_counts)], shadow=True)
plt.title('地图使用分布', fontsize=14, fontweight='bold')
# 图2:柱状图 - 武器类型伤害对比
plt.subplot(2, 4, 2)
weapon_type_damage = df_weapons.groupby('武器类型')['基础伤害'].mean().sort_values()
bars = plt.bar(weapon_type_damage.index, weapon_type_damage.values,
color=plt.cm.Spectral(np.linspace(0, 1, len(weapon_type_damage))))
plt.title('武器类型平均伤害', fontsize=14, fontweight='bold')
plt.ylabel('基础伤害')
plt.xticks(rotation=45, ha='right')
for i, (type_name, damage) in enumerate(weapon_type_damage.items()):
plt.text(i, damage + 1, f'{damage:.0f}', ha='center', va='bottom')
# 图3:横向柱状图 - 热门武器TOP10
plt.subplot(2, 4, 3)
weapon_usage = df_matches['主武器'].value_counts().head(10)
y_pos = np.arange(len(weapon_usage))
bars = plt.barh(y_pos, weapon_usage.values,
color=plt.cm.plasma(np.linspace(0, 1, len(weapon_usage))))
plt.yticks(y_pos, weapon_usage.index)
plt.xlabel('使用次数')
plt.title('热门武器TOP10', fontsize=14, fontweight='bold')
for i, v in enumerate(weapon_usage.values):
plt.text(v + 0.5, i, str(v), va='center')
# 图4:散点图 - 生存时间与击杀数关系
plt.subplot(2, 4, 4)
scatter = plt.scatter(df_matches['生存时间'], df_matches['击杀数'],
c=df_matches['最终排名'], cmap='RdYlGn_r',
s=df_matches['造成伤害']/10, alpha=0.6,
edgecolors='black', linewidth=0.5)
plt.xlabel('生存时间(分钟)')
plt.ylabel('击杀数')
plt.title('生存时间与击杀数关系', fontsize=14, fontweight='bold')
cbar = plt.colorbar(scatter, label='最终排名')
# 添加趋势线
z = np.polyfit(df_matches['生存时间'], df_matches['击杀数'], 1)
p = np.poly1d(z)
plt.plot(df_matches['生存时间'].sort_values(),
p(df_matches['生存时间'].sort_values()), "r--", alpha=0.8, linewidth=2)
# 图5:箱线图 - 不同段位的击杀表现
plt.subplot(2, 4, 5)
rank_order = ['青铜', '白银', '黄金', '铂金', '钻石', '王牌', '战神']
df_matches['段位'] = pd.Categorical(df_matches['段位'], categories=rank_order, ordered=True)
df_matches_sorted = df_matches.sort_values('段位')
# 创建箱线图数据
box_data = []
box_positions = []
box_labels = []
for i, rank in enumerate(rank_order):
rank_data = df_matches_sorted[df_matches_sorted['段位'] == rank]['击杀数'].values
if len(rank_data) > 0:
box_data.append(rank_data)
box_positions.append(i)
box_labels.append(rank)
box = plt.boxplot(box_data, positions=box_positions, patch_artist=True)
# 设置颜色
colors_rank = ['#CD7F32', '#C0C0C0', '#FFD700', '#E5E4E2', '#B9F2FF', '#800080', '#FF0000']
for patch, pos in zip(box['boxes'], box_positions):
patch.set_facecolor(colors_rank[pos])
plt.xticks(box_positions, box_labels)
plt.ylabel('击杀数')
plt.title('不同段位击杀数分布', fontsize=14, fontweight='bold')
# 图6:热力图 - 地图与模式的吃鸡率
plt.subplot(2, 4, 6)
# 创建地图-模式吃鸡率矩阵
pivot_data = df_matches.pivot_table(
values='吃鸡',
index='地图',
columns='模式',
aggfunc='mean'
) * 100 # 转换为百分比
sns.heatmap(pivot_data, annot=True, fmt='.1f', cmap='YlOrRd',
cbar_kws={'label': '吃鸡率(%)'}, square=True)
plt.title('地图-模式吃鸡率热力图', fontsize=14, fontweight='bold')
# 图7:面积图 - 游戏进程中的资源消耗
plt.subplot(2, 4, 7)
# 模拟游戏进程数据
time_points = np.arange(0, 36, 3)
alive_players = 100 * np.exp(-time_points/10)
safe_zone = 100 * (1 - time_points/35)**2
plt.fill_between(time_points, 0, alive_players, alpha=0.6, color='red', label='存活玩家')
plt.fill_between(time_points, 0, safe_zone, alpha=0.6, color='blue', label='安全区面积%')
plt.xlabel('游戏时间(分钟)')
plt.ylabel('数量/百分比')
plt.title('典型游戏进程曲线', fontsize=14, fontweight='bold')
plt.legend()
plt.grid(True, alpha=0.3)
# 图8:雷达图 - 顶尖玩家综合能力
plt.subplot(2, 4, 8, projection='polar')
# 选择综合评分最高的4名玩家
top_players = df_matches.groupby('玩家ID')['综合评分'].mean().nlargest(4).index
angles = np.linspace(0, 2 * np.pi, 6, endpoint=False).tolist()
angles += angles[:1]
metrics = ['击杀能力', '生存能力', '伤害输出', '移动效率', '精准度', '支援能力']
for i, player in enumerate(top_players):
player_data = df_matches[df_matches['玩家ID'] == player]
values = [
min(player_data['击杀数'].mean() / 8, 1), # 标准化到0-1
min(player_data['生存时间'].mean() / 30, 1),
min(player_data['每分钟伤害'].mean() / 50, 1),
min(player_data['每公里击杀'].mean() / 2, 1),
min(player_data['爆头数'].mean() / 3, 1),
min(player_data['助攻数'].mean() / 3, 1)
]
values += values[:1]
plt.plot(angles, values, 'o-', linewidth=2, label=player)
plt.fill(angles, values, alpha=0.15)
plt.xticks(angles[:-1], metrics, size=9)
plt.ylim(0, 1)
plt.legend(loc='upper right', bbox_to_anchor=(1.3, 1.1), fontsize=8)
plt.title('顶尖玩家能力六维图', fontsize=14, fontweight='bold', y=1.08)
# 调整布局并保存
plt.suptitle('PUBG数据分析(8种不同视图)', fontsize=20, fontweight='bold')
plt.tight_layout()
# 保存图表
plt.savefig('PUBG数据分析_8种视图.png', dpi=150, bbox_inches='tight')
print(f"图表已保存为:PUBG数据分析_8种视图.png")
# 尝试显示
try:
plt.show()
except:
print("图表无法在当前环境显示,但已保存为PNG文件")
# ==================== 4. 统计报告 ====================
print("\n=== 数据分析报告 ===")
print(f"\n基础统计:")
print(f"- 总比赛场次:{len(df_matches)}")
print(f"- 参与玩家数:{df_matches['玩家ID'].nunique()}")
print(f"- 平均击杀数:{df_matches['击杀数'].mean():.2f}")
print(f"- 平均生存时间:{df_matches['生存时间'].mean():.1f}分钟")
print(f"- 平均伤害:{df_matches['造成伤害'].mean():.1f}")
print(f"\n吃鸡统计:")
winner_count = df_matches['吃鸡'].sum()
print(f"- 吃鸡次数:{winner_count}次")
print(f"- 吃鸡率:{winner_count/len(df_matches)*100:.1f}%")
print(f"- 前十率:{df_matches['前十'].mean()*100:.1f}%")
print(f"\n武器使用TOP3:")
for i, (weapon, count) in enumerate(weapon_usage.head(3).items(), 1):
weapon_info = df_weapons[df_weapons['武器名称'] == weapon]
if not weapon_info.empty:
damage = weapon_info['基础伤害'].values[0]
print(f"{i}. {weapon}: {count}次使用(基础伤害:{damage})")
print(f"\n地图表现排名:")
map_stats = df_matches.groupby('地图').agg({
'击杀数': 'mean',
'前十': 'mean',
'吃鸡': 'mean'
}).round(2)
for map_name, stats in map_stats.iterrows():
print(f"- {map_name}: 平均击杀{stats['击杀数']:.1f}, 前十率{stats['前十']*100:.1f}%, 吃鸡率{stats['吃鸡']*100:.1f}%")
# 模式分析
mode_stats = df_matches.groupby('模式').agg({
'击杀数': 'mean',
'生存时间': 'mean',
'吃鸡': 'mean'
}).round(2)
print(f"\n游戏模式分析:")
for mode, stats in mode_stats.iterrows():
print(f"- {mode}: 平均击杀{stats['击杀数']:.1f}, 平均生存{stats['生存时间']:.1f}分钟, 吃鸡率{stats['吃鸡']*100:.1f}%")
# ==================== 5. 保存结果 ====================
# 保存数据到Excel
try:
with pd.ExcelWriter('PUBG数据分析结果_8种视图.xlsx', engine='openpyxl') as writer:
df_weapons.to_excel(writer, sheet_name='武器数据', index=False)
df_matches.to_excel(writer, sheet_name='比赛数据', index=False)
# 统计汇总
summary_data = {
'统计项': ['总比赛数', '平均击杀', '平均伤害', '吃鸡率', '前十率',
'平均生存时间', '最高击杀', '最高伤害'],
'数值': [
len(df_matches),
f"{df_matches['击杀数'].mean():.2f}",
f"{df_matches['造成伤害'].mean():.1f}",
f"{winner_count/len(df_matches)*100:.1f}%",
f"{df_matches['前十'].mean()*100:.1f}%",
f"{df_matches['生存时间'].mean():.1f}分钟",
f"{df_matches['击杀数'].max()}",
f"{df_matches['造成伤害'].max()}"
]
}
pd.DataFrame(summary_data).to_excel(writer, sheet_name='统计汇总', index=False)
# 武器统计
weapon_stats = df_matches['主武器'].value_counts().reset_index()
weapon_stats.columns = ['武器', '使用次数']
weapon_stats['使用率%'] = (weapon_stats['使用次数'] / len(df_matches) * 100).round(1)
weapon_stats.to_excel(writer, sheet_name='武器使用统计', index=False)
# 地图模式统计
map_mode_stats = df_matches.groupby(['地图', '模式']).agg({
'击杀数': 'mean',
'吃鸡': ['sum', 'mean'],
'前十': 'mean'
}).round(2)
map_mode_stats.to_excel(writer, sheet_name='地图模式统计')
print(f"Excel文件已保存为:PUBG数据分析结果_8种视图.xlsx")
except Exception as e:
print(f"Excel保存失败:{e}")
# 生成文本报告
report = f"""
PUBG数据分析报告(8种不同视图版本)
生成时间:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
【可视化图表类型】
1. 饼图 - 地图使用分布
2. 柱状图 - 武器类型平均伤害
3. 横向柱状图 - 热门武器排行
4. 散点图 - 生存时间与击杀数相关性
5. 箱线图 - 段位击杀数分布
6. 热力图 - 地图模式吃鸡率
7. 面积图 - 游戏进程曲线
8. 雷达图 - 顶尖玩家能力分析
【数据分析结果】
1. 数据概览
- 分析期间:{df_matches['日期'].min()} 至 {df_matches['日期'].max()}
- 总比赛场次:{len(df_matches)}场
- 涉及玩家:{df_matches['玩家ID'].nunique()}人
2. 核心指标
- 平均击杀数:{df_matches['击杀数'].mean():.2f}
- 平均伤害:{df_matches['造成伤害'].mean():.1f}
- 平均生存时间:{df_matches['生存时间'].mean():.1f}分钟
- 吃鸡率:{winner_count/len(df_matches)*100:.1f}%
- 前十率:{df_matches['前十'].mean()*100:.1f}%
3. 热门武器
- {weapon_usage.index[0]}({weapon_usage.values[0]}次)
- {weapon_usage.index[1]}({weapon_usage.values[1]}次)
- {weapon_usage.index[2]}({weapon_usage.values[2]}次)
4. 最佳表现
- 单场最高击杀:{df_matches['击杀数'].max()}个
- 单场最高伤害:{df_matches['造成伤害'].max()}
- 最高综合评分:{df_matches['综合评分'].max():.0f}
5. 关键发现
- 生存时间与击杀数呈正相关
- 高段位玩家击杀数明显高于低段位
- 四排模式吃鸡率最高,单排难度最大
- M416是最受欢迎的武器选择
"""
try:
with open('PUBG分析报告_8种视图.txt', 'w', encoding='utf-8') as f:
f.write(report)
print(f"报告已保存为:PUBG分析报告_8种视图.txt")
except Exception as e:
print(f"报告保存失败:{e}")
print("\n=== 分析完成!===")
print("8种不同类型的可视化图表已生成,包括:饼图、柱状图、横向柱状图、散点图、箱线图、热力图、面积图、雷达图。")
这个PUBG数据分析系统包含了8种完全不同类型的可视化图表:
- 饼图 - 展示地图使用分布
- 柱状图 - 比较武器类型平均伤害
- 横向柱状图 - 热门武器TOP10排行
- 散点图 - 生存时间与击杀数相关性(点大小表示伤害)
- 箱线图 - 不同段位的击杀数分布
- 热力图 - 地图与模式的吃鸡率矩阵
- 面积图 - 游戏进程中存活玩家和安全区变化
- 雷达图 - 顶尖玩家六维能力分析
每种图表都针对PUBG的特定数据特征进行了优化,能够全面展示游戏的各个方面。
import pandas as pd
import numpy as np
import matplotlib
matplotlib.use('Agg') # 设置非交互式后端,避免错误
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
# 配置matplotlib
plt.rcParams['font.sans-serif'] = ['SimHei'] # 中文显示
plt.rcParams['axes.unicode_minus'] = False # 负号显示
print("=== PUBG数据分析系统(8种不同视图)===")
# ==================== 1. 内置数据集 ====================
# 武器数据
weapons_data = {
'武器名称': ['M416', 'AKM', 'SCAR-L', 'M24', 'AWM', 'UZI', 'Vector', 'S686', 'Pan', 'M249',
'Kar98k', 'SKS', 'Mini14', 'UMP45', 'Tommy Gun', 'VSS', 'Groza', 'MK14'],
'武器类型': ['突击步枪', '突击步枪', '突击步枪', '狙击枪', '狙击枪', '冲锋枪', '冲锋枪', '霰弹枪', '近战武器', '机枪',
'狙击枪', '射手步枪', '射手步枪', '冲锋枪', '冲锋枪', '狙击枪', '突击步枪', '射手步枪'],
'子弹类型': ['5.56mm', '7.62mm', '5.56mm', '7.62mm', '.300马格南', '9mm', '.45ACP', '12号', '无', '5.56mm',
'7.62mm', '7.62mm', '5.56mm', '.45ACP', '.45ACP', '9mm', '7.62mm', '7.62mm'],
'基础伤害': [43, 49, 43, 79, 105, 26, 31, 25, 80, 45, 75, 53, 46, 39, 40, 41, 49, 61],
'射速': [0.086, 0.1, 0.096, 1.8, 1.85, 0.048, 0.055, 0.2, 0, 0.075, 1.9, 0.09, 0.1, 0.092, 0.086, 0.086, 0.08, 0.09],
'弹匣容量': [30, 30, 30, 5, 5, 25, 25, 2, 0, 100, 5, 10, 20, 25, 50, 10, 30, 10],
'有效射程': [60, 60, 60, 100, 100, 25, 25, 15, 1, 75, 100, 80, 70, 40, 35, 100, 60, 90],
'获取难度': ['常见', '常见', '常见', '稀有', '空投', '常见', '常见', '常见', '常见', '空投', '稀有', '稀有', '常见', '常见', '常见', '稀有', '空投', '空投']
}
# 比赛数据(100条记录)
np.random.seed(42)
match_count = 100
# 先生成基础数据
modes = np.random.choice(['单排', '双排', '四排'], match_count, p=[0.2, 0.3, 0.5])
matches_data = {
'比赛ID': [f'MATCH{i:03d}' for i in range(1, match_count + 1)],
'日期': pd.date_range('2024-01-01', periods=match_count, freq='4H').strftime('%Y-%m-%d').tolist(),
'玩家ID': [f'Player{i%25 + 1}' for i in range(match_count)],
'地图': np.random.choice(['艾伦格', '米拉玛', '萨诺', '维寒迪', '帕拉莫'], match_count, p=[0.3, 0.2, 0.2, 0.2, 0.1]),
'模式': modes,
'最终排名': np.random.randint(1, 101, match_count),
'击杀数': np.random.poisson(2, match_count),
'助攻数': np.random.poisson(1, match_count),
'生存时间': np.random.randint(1, 35, match_count),
'造成伤害': np.random.randint(50, 1200, match_count),
'移动距离': np.random.uniform(0.5, 10, match_count),
'治疗次数': np.random.randint(0, 15, match_count),
'爆头数': np.random.poisson(0.8, match_count),
'载具摧毁': np.random.poisson(0.3, match_count),
'主武器': np.random.choice(['M416', 'AKM', 'SCAR-L', 'M24', 'AWM', 'UZI', 'Vector', 'M249', 'Kar98k', 'SKS'], match_count),
'段位': np.random.choice(['青铜', '白银', '黄金', '铂金', '钻石', '王牌', '战神'], match_count,
p=[0.15, 0.25, 0.25, 0.20, 0.10, 0.04, 0.01])
}
# 根据模式生成队伍人数
team_sizes = []
for mode in modes:
if mode == '单排':
team_sizes.append(1)
elif mode == '双排':
team_sizes.append(2)
else: # 四排
team_sizes.append(4)
matches_data['队伍人数'] = team_sizes
# 调整数据逻辑
for i in range(match_count):
if matches_data['最终排名'][i] <= 10: # 前10名
matches_data['击杀数'][i] = np.random.randint(3, 12)
matches_data['造成伤害'][i] = np.random.randint(500, 1500)
matches_data['生存时间'][i] = np.random.randint(20, 35)
elif matches_data['最终排名'][i] <= 30: # 11-30名
matches_data['击杀数'][i] = np.random.randint(1, 6)
matches_data['造成伤害'][i] = np.random.randint(200, 700)
matches_data['生存时间'][i] = np.random.randint(10, 25)
else: # 30名以后
matches_data['击杀数'][i] = np.random.randint(0, 3)
matches_data['造成伤害'][i] = np.random.randint(0, 400)
matches_data['生存时间'][i] = np.random.randint(1, 15)
# 创建DataFrame
df_weapons = pd.DataFrame(weapons_data)
df_matches = pd.DataFrame(matches_data)
# ==================== 2. 数据预处理 ====================
print("\n数据预处理中...")
# 计算KD比率
df_matches['KD'] = df_matches['击杀数'] / np.maximum(df_matches['队伍人数'], 1)
# 计算效率指标
df_matches['每分钟伤害'] = df_matches['造成伤害'] / np.maximum(df_matches['生存时间'], 1)
df_matches['每公里击杀'] = df_matches['击杀数'] / np.maximum(df_matches['移动距离'], 0.1)
# 计算吃鸡率和前十率
df_matches['吃鸡'] = (df_matches['最终排名'] == 1).astype(int)
df_matches['前十'] = (df_matches['最终排名'] <= 10).astype(int)
# 综合评分
df_matches['综合评分'] = (
df_matches['击杀数'] * 20 +
df_matches['造成伤害'] * 0.1 +
(101 - df_matches['最终排名']) * 2 +
df_matches['助攻数'] * 10 +
df_matches['爆头数'] * 15
)
# ==================== 3. 创建8种不同类型的可视化图表 ====================
print("\n生成可视化图表...")
# 创建图形 - 2x4布局
plt.figure(figsize=(20, 12))
# 图1:饼图 - 地图使用分布
plt.subplot(2, 4, 1)
map_counts = df_matches['地图'].value_counts()
colors_map = ['#8B4513', '#F4A460', '#90EE90', '#87CEEB', '#DDA0DD']
plt.pie(map_counts.values, labels=map_counts.index, autopct='%1.1f%%',
startangle=90, colors=colors_map[:len(map_counts)], shadow=True)
plt.title('地图使用分布', fontsize=14, fontweight='bold')
# 图2:柱状图 - 武器类型伤害对比
plt.subplot(2, 4, 2)
weapon_type_damage = df_weapons.groupby('武器类型')['基础伤害'].mean().sort_values()
bars = plt.bar(weapon_type_damage.index, weapon_type_damage.values,
color=plt.cm.Spectral(np.linspace(0, 1, len(weapon_type_damage))))
plt.title('武器类型平均伤害', fontsize=14, fontweight='bold')
plt.ylabel('基础伤害')
plt.xticks(rotation=45, ha='right')
for i, (type_name, damage) in enumerate(weapon_type_damage.items()):
plt.text(i, damage + 1, f'{damage:.0f}', ha='center', va='bottom')
# 图3:横向柱状图 - 热门武器TOP10
plt.subplot(2, 4, 3)
weapon_usage = df_matches['主武器'].value_counts().head(10)
y_pos = np.arange(len(weapon_usage))
bars = plt.barh(y_pos, weapon_usage.values,
color=plt.cm.plasma(np.linspace(0, 1, len(weapon_usage))))
plt.yticks(y_pos, weapon_usage.index)
plt.xlabel('使用次数')
plt.title('热门武器TOP10', fontsize=14, fontweight='bold')
for i, v in enumerate(weapon_usage.values):
plt.text(v + 0.5, i, str(v), va='center')
# 图4:散点图 - 生存时间与击杀数关系
plt.subplot(2, 4, 4)
scatter = plt.scatter(df_matches['生存时间'], df_matches['击杀数'],
c=df_matches['最终排名'], cmap='RdYlGn_r',
s=df_matches['造成伤害']/10, alpha=0.6,
edgecolors='black', linewidth=0.5)
plt.xlabel('生存时间(分钟)')
plt.ylabel('击杀数')
plt.title('生存时间与击杀数关系', fontsize=14, fontweight='bold')
cbar = plt.colorbar(scatter, label='最终排名')
# 添加趋势线
z = np.polyfit(df_matches['生存时间'], df_matches['击杀数'], 1)
p = np.poly1d(z)
plt.plot(df_matches['生存时间'].sort_values(),
p(df_matches['生存时间'].sort_values()), "r--", alpha=0.8, linewidth=2)
# 图5:箱线图 - 不同段位的击杀表现
plt.subplot(2, 4, 5)
rank_order = ['青铜', '白银', '黄金', '铂金', '钻石', '王牌', '战神']
df_matches['段位'] = pd.Categorical(df_matches['段位'], categories=rank_order, ordered=True)
df_matches_sorted = df_matches.sort_values('段位')
# 创建箱线图数据
box_data = []
box_positions = []
box_labels = []
for i, rank in enumerate(rank_order):
rank_data = df_matches_sorted[df_matches_sorted['段位'] == rank]['击杀数'].values
if len(rank_data) > 0:
box_data.append(rank_data)
box_positions.append(i)
box_labels.append(rank)
box = plt.boxplot(box_data, positions=box_positions, patch_artist=True)
# 设置颜色
colors_rank = ['#CD7F32', '#C0C0C0', '#FFD700', '#E5E4E2', '#B9F2FF', '#800080', '#FF0000']
for patch, pos in zip(box['boxes'], box_positions):
patch.set_facecolor(colors_rank[pos])
plt.xticks(box_positions, box_labels)
plt.ylabel('击杀数')
plt.title('不同段位击杀数分布', fontsize=14, fontweight='bold')
# 图6:热力图 - 地图与模式的吃鸡率
plt.subplot(2, 4, 6)
# 创建地图-模式吃鸡率矩阵
pivot_data = df_matches.pivot_table(
values='吃鸡',
index='地图',
columns='模式',
aggfunc='mean'
) * 100 # 转换为百分比
sns.heatmap(pivot_data, annot=True, fmt='.1f', cmap='YlOrRd',
cbar_kws={'label': '吃鸡率(%)'}, square=True)
plt.title('地图-模式吃鸡率热力图', fontsize=14, fontweight='bold')
# 图7:面积图 - 游戏进程中的资源消耗
plt.subplot(2, 4, 7)
# 模拟游戏进程数据
time_points = np.arange(0, 36, 3)
alive_players = 100 * np.exp(-time_points/10)
safe_zone = 100 * (1 - time_points/35)**2
plt.fill_between(time_points, 0, alive_players, alpha=0.6, color='red', label='存活玩家')
plt.fill_between(time_points, 0, safe_zone, alpha=0.6, color='blue', label='安全区面积%')
plt.xlabel('游戏时间(分钟)')
plt.ylabel('数量/百分比')
plt.title('典型游戏进程曲线', fontsize=14, fontweight='bold')
plt.legend()
plt.grid(True, alpha=0.3)
# 图8:雷达图 - 顶尖玩家综合能力
plt.subplot(2, 4, 8, projection='polar')
# 选择综合评分最高的4名玩家
top_players = df_matches.groupby('玩家ID')['综合评分'].mean().nlargest(4).index
angles = np.linspace(0, 2 * np.pi, 6, endpoint=False).tolist()
angles += angles[:1]
metrics = ['击杀能力', '生存能力', '伤害输出', '移动效率', '精准度', '支援能力']
for i, player in enumerate(top_players):
player_data = df_matches[df_matches['玩家ID'] == player]
values = [
min(player_data['击杀数'].mean() / 8, 1), # 标准化到0-1
min(player_data['生存时间'].mean() / 30, 1),
min(player_data['每分钟伤害'].mean() / 50, 1),
min(player_data['每公里击杀'].mean() / 2, 1),
min(player_data['爆头数'].mean() / 3, 1),
min(player_data['助攻数'].mean() / 3, 1)
]
values += values[:1]
plt.plot(angles, values, 'o-', linewidth=2, label=player)
plt.fill(angles, values, alpha=0.15)
plt.xticks(angles[:-1], metrics, size=9)
plt.ylim(0, 1)
plt.legend(loc='upper right', bbox_to_anchor=(1.3, 1.1), fontsize=8)
plt.title('顶尖玩家能力六维图', fontsize=14, fontweight='bold', y=1.08)
# 调整布局并保存
plt.suptitle('PUBG数据分析(8种不同视图)', fontsize=20, fontweight='bold')
plt.tight_layout()
# 保存图表
plt.savefig('PUBG数据分析_8种视图.png', dpi=150, bbox_inches='tight')
print(f"图表已保存为:PUBG数据分析_8种视图.png")
# 尝试显示
try:
plt.show()
except:
print("图表无法在当前环境显示,但已保存为PNG文件")
# ==================== 4. 统计报告 ====================
print("\n=== 数据分析报告 ===")
print(f"\n基础统计:")
print(f"- 总比赛场次:{len(df_matches)}")
print(f"- 参与玩家数:{df_matches['玩家ID'].nunique()}")
print(f"- 平均击杀数:{df_matches['击杀数'].mean():.2f}")
print(f"- 平均生存时间:{df_matches['生存时间'].mean():.1f}分钟")
print(f"- 平均伤害:{df_matches['造成伤害'].mean():.1f}")
print(f"\n吃鸡统计:")
winner_count = df_matches['吃鸡'].sum()
print(f"- 吃鸡次数:{winner_count}次")
print(f"- 吃鸡率:{winner_count/len(df_matches)*100:.1f}%")
print(f"- 前十率:{df_matches['前十'].mean()*100:.1f}%")
print(f"\n武器使用TOP3:")
for i, (weapon, count) in enumerate(weapon_usage.head(3).items(), 1):
weapon_info = df_weapons[df_weapons['武器名称'] == weapon]
if not weapon_info.empty:
damage = weapon_info['基础伤害'].values[0]
print(f"{i}. {weapon}: {count}次使用(基础伤害:{damage})")
print(f"\n地图表现排名:")
map_stats = df_matches.groupby('地图').agg({
'击杀数': 'mean',
'前十': 'mean',
'吃鸡': 'mean'
}).round(2)
for map_name, stats in map_stats.iterrows():
print(f"- {map_name}: 平均击杀{stats['击杀数']:.1f}, 前十率{stats['前十']*100:.1f}%, 吃鸡率{stats['吃鸡']*100:.1f}%")
# 模式分析
mode_stats = df_matches.groupby('模式').agg({
'击杀数': 'mean',
'生存时间': 'mean',
'吃鸡': 'mean'
}).round(2)
print(f"\n游戏模式分析:")
for mode, stats in mode_stats.iterrows():
print(f"- {mode}: 平均击杀{stats['击杀数']:.1f}, 平均生存{stats['生存时间']:.1f}分钟, 吃鸡率{stats['吃鸡']*100:.1f}%")
# ==================== 5. 保存结果 ====================
# 保存数据到Excel
try:
with pd.ExcelWriter('PUBG数据分析结果_8种视图.xlsx', engine='openpyxl') as writer:
df_weapons.to_excel(writer, sheet_name='武器数据', index=False)
df_matches.to_excel(writer, sheet_name='比赛数据', index=False)
# 统计汇总
summary_data = {
'统计项': ['总比赛数', '平均击杀', '平均伤害', '吃鸡率', '前十率',
'平均生存时间', '最高击杀', '最高伤害'],
'数值': [
len(df_matches),
f"{df_matches['击杀数'].mean():.2f}",
f"{df_matches['造成伤害'].mean():.1f}",
f"{winner_count/len(df_matches)*100:.1f}%",
f"{df_matches['前十'].mean()*100:.1f}%",
f"{df_matches['生存时间'].mean():.1f}分钟",
f"{df_matches['击杀数'].max()}",
f"{df_matches['造成伤害'].max()}"
]
}
pd.DataFrame(summary_data).to_excel(writer, sheet_name='统计汇总', index=False)
# 武器统计
weapon_stats = df_matches['主武器'].value_counts().reset_index()
weapon_stats.columns = ['武器', '使用次数']
weapon_stats['使用率%'] = (weapon_stats['使用次数'] / len(df_matches) * 100).round(1)
weapon_stats.to_excel(writer, sheet_name='武器使用统计', index=False)
# 地图模式统计
map_mode_stats = df_matches.groupby(['地图', '模式']).agg({
'击杀数': 'mean',
'吃鸡': ['sum', 'mean'],
'前十': 'mean'
}).round(2)
map_mode_stats.to_excel(writer, sheet_name='地图模式统计')
print(f"Excel文件已保存为:PUBG数据分析结果_8种视图.xlsx")
except Exception as e:
print(f"Excel保存失败:{e}")
# 生成文本报告
report = f"""
PUBG数据分析报告(8种不同视图版本)
生成时间:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
【可视化图表类型】
1. 饼图 - 地图使用分布
2. 柱状图 - 武器类型平均伤害
3. 横向柱状图 - 热门武器排行
4. 散点图 - 生存时间与击杀数相关性
5. 箱线图 - 段位击杀数分布
6. 热力图 - 地图模式吃鸡率
7. 面积图 - 游戏进程曲线
8. 雷达图 - 顶尖玩家能力分析
【数据分析结果】
1. 数据概览
- 分析期间:{df_matches['日期'].min()} 至 {df_matches['日期'].max()}
- 总比赛场次:{len(df_matches)}场
- 涉及玩家:{df_matches['玩家ID'].nunique()}人
2. 核心指标
- 平均击杀数:{df_matches['击杀数'].mean():.2f}
- 平均伤害:{df_matches['造成伤害'].mean():.1f}
- 平均生存时间:{df_matches['生存时间'].mean():.1f}分钟
- 吃鸡率:{winner_count/len(df_matches)*100:.1f}%
- 前十率:{df_matches['前十'].mean()*100:.1f}%
3. 热门武器
- {weapon_usage.index[0]}({weapon_usage.values[0]}次)
- {weapon_usage.index[1]}({weapon_usage.values[1]}次)
- {weapon_usage.index[2]}({weapon_usage.values[2]}次)
4. 最佳表现
- 单场最高击杀:{df_matches['击杀数'].max()}个
- 单场最高伤害:{df_matches['造成伤害'].max()}
- 最高综合评分:{df_matches['综合评分'].max():.0f}
5. 关键发现
- 生存时间与击杀数呈正相关
- 高段位玩家击杀数明显高于低段位
- 四排模式吃鸡率最高,单排难度最大
- M416是最受欢迎的武器选择
"""
try:
with open('PUBG分析报告_8种视图.txt', 'w', encoding='utf-8') as f:
f.write(report)
print(f"报告已保存为:PUBG分析报告_8种视图.txt")
except Exception as e:
print(f"报告保存失败:{e}")
print("\n=== 分析完成!===")
print("8种不同类型的可视化图表已生成,包括:饼图、柱状图、横向柱状图、散点图、箱线图、热力图、面积图、雷达图。")
- 先生成模式数据
- 单独使用循环生成队伍人数列表
- 将队伍人数列表添加到字典中
这样就避免了在字典定义时引用还未创建的数据的问题。
import pandas as pd
import numpy as np
import matplotlib
matplotlib.use('Agg') # 设置非交互式后端
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
# 配置matplotlib
plt.rcParams['font.sans-serif'] = ['SimHei'] # 中文显示
plt.rcParams['axes.unicode_minus'] = False # 负号显示
print("=== 三角洲行动数据分析系统(简化版)===")
# ==================== 1. 内置数据集 ====================
# 职业数据
operators_data = {
'职业': ['突击兵', '医疗兵', '工程兵', '侦察兵', '支援兵'],
'主武器': ['突击步枪', '冲锋枪', '霰弹枪', '狙击枪', '机枪'],
'移动速度': [100, 110, 90, 105, 85],
'生命值': [100, 90, 110, 85, 120],
'护甲值': [100, 80, 120, 70, 130]
}
# 武器数据(简化版)
weapons_data = {
'武器名称': ['M4A1', 'AK-47', 'MP5', 'AWP', 'M249', 'SPAS-12'],
'武器类型': ['突击步枪', '突击步枪', '冲锋枪', '狙击枪', '机枪', '霰弹枪'],
'伤害': [45, 50, 35, 100, 48, 80],
'射速': [700, 600, 800, 50, 650, 100],
'弹匣': [30, 30, 30, 10, 100, 8]
}
# 比赛数据(60条记录)
np.random.seed(42)
match_count = 60
# 生成基础数据
matches_data = {
'比赛ID': [f'GAME{i:03d}' for i in range(1, match_count + 1)],
'玩家': [f'玩家{i%15 + 1}' for i in range(match_count)],
'职业': np.random.choice(['突击兵', '医疗兵', '工程兵', '侦察兵', '支援兵'], match_count),
'地图': np.random.choice(['沙漠', '雪地', '城市'], match_count),
'模式': np.random.choice(['团队死斗', '爆破', '占领'], match_count),
'击杀': np.random.randint(0, 20, match_count),
'死亡': np.random.randint(0, 15, match_count),
'助攻': np.random.randint(0, 10, match_count),
'分数': np.random.randint(500, 5000, match_count),
'胜负': np.random.choice(['胜', '负'], match_count),
'段位': np.random.choice(['青铜', '白银', '黄金', '铂金', '钻石'], match_count, p=[0.2, 0.3, 0.3, 0.15, 0.05])
}
# 创建DataFrame
df_operators = pd.DataFrame(operators_data)
df_weapons = pd.DataFrame(weapons_data)
df_matches = pd.DataFrame(matches_data)
# ==================== 2. 数据预处理 ====================
print("\n数据预处理中...")
# 计算KD
df_matches['KD'] = df_matches['击杀'] / np.maximum(df_matches['死亡'], 1)
# ==================== 3. 创建8个简单的可视化图表 ====================
print("\n生成简化版可视化图表...")
# 创建图形
plt.figure(figsize=(16, 10))
# 图1:简单饼图 - 职业分布
plt.subplot(2, 4, 1)
job_counts = df_matches['职业'].value_counts()
plt.pie(job_counts.values, labels=job_counts.index, autopct='%1.0f%%')
plt.title('职业分布')
# 图2:简单柱状图 - 地图胜率
plt.subplot(2, 4, 2)
map_winrate = df_matches.groupby('地图')['胜负'].apply(lambda x: (x == '胜').mean() * 100)
plt.bar(map_winrate.index, map_winrate.values, color=['tan', 'lightblue', 'gray'])
plt.ylabel('胜率%')
plt.title('地图胜率')
# 图3:简单条形图 - 武器伤害
plt.subplot(2, 4, 3)
plt.barh(df_weapons['武器名称'], df_weapons['伤害'], color='orange')
plt.xlabel('伤害')
plt.title('武器伤害')
# 图4:简单散点图 - 击杀vs分数
plt.subplot(2, 4, 4)
plt.scatter(df_matches['击杀'], df_matches['分数'], alpha=0.5)
plt.xlabel('击杀')
plt.ylabel('分数')
plt.title('击杀与分数')
# 图5:简单折线图 - 段位平均KD
plt.subplot(2, 4, 5)
rank_kd = df_matches.groupby('段位')['KD'].mean()
rank_order = ['青铜', '白银', '黄金', '铂金', '钻石']
rank_kd = rank_kd.reindex([r for r in rank_order if r in rank_kd.index])
plt.plot(rank_kd.index, rank_kd.values, 'o-', color='red', linewidth=2, markersize=8)
plt.ylabel('平均KD')
plt.title('段位KD趋势')
# 图6:简单直方图 - KD分布
plt.subplot(2, 4, 6)
plt.hist(df_matches['KD'], bins=15, color='green', alpha=0.7)
plt.xlabel('KD值')
plt.ylabel('频次')
plt.title('KD分布')
# 图7:简单堆叠柱状图 - 模式表现
plt.subplot(2, 4, 7)
mode_stats = df_matches.groupby(['模式', '胜负']).size().unstack(fill_value=0)
mode_stats.plot(kind='bar', stacked=True, ax=plt.gca(), color=['red', 'green'])
plt.ylabel('场次')
plt.title('模式胜负统计')
plt.legend(['负', '胜'])
# 图8:简单面积图 - 职业属性
plt.subplot(2, 4, 8)
x = range(len(df_operators))
plt.fill_between(x, 0, df_operators['生命值'], alpha=0.3, label='生命值')
plt.fill_between(x, 0, df_operators['护甲值']/2, alpha=0.3, label='护甲值/2')
plt.xticks(x, df_operators['职业'], rotation=45)
plt.ylabel('数值')
plt.title('职业属性')
plt.legend()
# 调整布局
plt.suptitle('三角洲行动数据分析(简化版)', fontsize=16)
plt.tight_layout()
# 保存图表
plt.savefig('三角洲行动数据分析_简化版.png', dpi=120, bbox_inches='tight')
print(f"图表已保存为:三角洲行动数据分析_简化版.png")
# 尝试显示
try:
plt.show()
except:
print("图表无法显示,但已保存为PNG文件")
# ==================== 4. 简单统计报告 ====================
print("\n=== 数据分析报告 ===")
print(f"\n基础数据:")
print(f"- 总场次:{len(df_matches)}")
print(f"- 平均击杀:{df_matches['击杀'].mean():.1f}")
print(f"- 平均KD:{df_matches['KD'].mean():.2f}")
print(f"- 胜率:{(df_matches['胜负'] == '胜').mean() * 100:.1f}%")
print(f"\n职业使用率:")
for job, count in job_counts.items():
print(f"- {job}: {count}次 ({count/len(df_matches)*100:.0f}%)")
print(f"\n地图胜率:")
for map_name, winrate in map_winrate.items():
print(f"- {map_name}: {winrate:.0f}%")
# ==================== 5. 保存结果 ====================
# 保存Excel
try:
with pd.ExcelWriter('三角洲行动数据_简化版.xlsx', engine='openpyxl') as writer:
df_operators.to_excel(writer, sheet_name='职业数据', index=False)
df_weapons.to_excel(writer, sheet_name='武器数据', index=False)
df_matches.to_excel(writer, sheet_name='比赛数据', index=False)
print(f"\nExcel已保存为:三角洲行动数据_简化版.xlsx")
except Exception as e:
print(f"Excel保存失败:{e}")
# 生成简单文本报告
report = f"""
三角洲行动数据分析报告(简化版)
生成时间:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
1. 总体数据
- 比赛场次:{len(df_matches)}
- 平均击杀:{df_matches['击杀'].mean():.1f}
- 平均死亡:{df_matches['死亡'].mean():.1f}
- 平均KD:{df_matches['KD'].mean():.2f}
- 总体胜率:{(df_matches['胜负'] == '胜').mean() * 100:.1f}%
2. 最受欢迎职业:{job_counts.index[0]}({job_counts.values[0]}次)
3. 最高胜率地图:{map_winrate.idxmax()}({map_winrate.max():.0f}%)
4. 段位分布
"""
rank_dist = df_matches['段位'].value_counts()
for rank in ['青铜', '白银', '黄金', '铂金', '钻石']:
if rank in rank_dist.index:
report += f" - {rank}:{rank_dist[rank]}人\n"
report += f"""
5. 武器数据
- 最高伤害:{df_weapons.loc[df_weapons['伤害'].idxmax(), '武器名称']}({df_weapons['伤害'].max()})
- 最高射速:{df_weapons.loc[df_weapons['射速'].idxmax(), '武器名称']}({df_weapons['射速'].max()})
"""
try:
with open('三角洲行动分析报告_简化版.txt', 'w', encoding='utf-8') as f:
f.write(report)
print(f"报告已保存为:三角洲行动分析报告_简化版.txt")
except Exception as e:
print(f"报告保存失败:{e}")
print("\n=== 分析完成!===")
print("8个简单视图已生成:饼图、柱状图、条形图、散点图、折线图、直方图、堆叠柱状图、面积图")
-
极简的8种视图:
- 饼图 - 职业分布(无复杂样式)
- 柱状图 - 地图胜率(简单颜色)
- 条形图 - 武器伤害(单色)
- 散点图 - 击杀vs分数(基础点)
- 折线图 - 段位KD趋势(简单线条)
- 直方图 - KD分布(单色)
- 堆叠柱状图 - 模式胜负(双色)
- 面积图 - 职业属性(透明填充)
-
简化的数据:
- 只有60条比赛记录
- 5个职业
- 6种武器
- 3张地图
- 基础的统计指标
-
最小化的视觉元素:
- 简单的颜色方案
- 基础的图表样式
- 最少的标注和装饰
- 清晰的标题
所有图表都使用最基础的matplotlib功能,没有复杂的样式和效果。