python - 可视化面对面记录的最佳方式是什么?
问题描述
我有一个数据框如下所示:
A = pd.DataFrame({'team':[1,2,3,2,1,1,3,4,1,2], 'opp_team':[2,1,2,3,3,4,1,1,2,1], 'result':[1,0,1,0,1,1,0,0,1,0]})
结果列有 1 代表胜利,0 代表失败。我想找出在图表上呈现头对头记录的最佳方式。
我在想一对情节,但我认为它不会奏效,因为它不会显示胜利和失败的计数。在上面的例子中,球队 1 与球队 2 交手 2 次,并且都赢了。因此,图表也应该显示计数。
我可以尝试什么来解决这个问题?
解决方案
只需将它们显示在 2 个单独的图表中,1 个图表显示对战记录的总数,另一个显示一个团队对另一个团队的总胜率(另一个团队的胜率 = 团队的输球率)。
为此,我认为需要对数据框进行重组,使其每行仅显示 1 个游戏 ID。为了便于分组,对 and 进行排序team
,opp_team
使得索引team
总是小于索引opp_team
我生成了一个样本数据集,我将如何总结和绘制它,供您参考:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
def generate_data(num_data=100, num_teams=4):
team = np.random.randint(1,1 + num_teams,num_data)
opp_team = np.random.randint(1,1 + num_teams,num_data)
while len(opp_team[opp_team == team]) > 0:
opp_team[opp_team == team] = np.random.randint(1,1 + num_teams,len(opp_team[opp_team == team]))
results = np.round(np.random.rand(100))
return team, opp_team, results
def reorder_team(team, opp_team, result):
if team > opp_team:
team, opp_team = opp_team, team
result = 1 - result
return team, opp_team, result
# Generate data and get summary by team match-ups
team, opp_team, results = generate_data()
df = pd.DataFrame(data={'team':team,'opp_team':opp_team,'results':results}, dtype='int')
df = pd.DataFrame(df.apply(lambda x : reorder_team(x['team'], x['opp_team'], x['results']),axis=1).to_list(),
columns=df.columns)
df[['team','opp_team']] = 'Team ' + df[['team','opp_team']].astype(str)
df_summary = df.groupby(['team','opp_team']).agg(['sum','count'])
df_summary.columns = ['wins', 'total']
df_summary.reset_index(inplace=True)
df_summary['team_winrate'] = (df_summary['wins'] / df_summary['total'])
df_summary['opp_team_winrate'] = 1 - df_summary['team_winrate']
产生:
您可以使用以下脚本绘制它们(或使用您喜欢的库编写自己的脚本):
fig, (ax_count, ax_win) = plt.subplots(1,2, figsize=(12,6))
y_locs = list(range(len(df_summary)))
ax_count.barh(y_locs, width=df_summary['total'], color='tab:gray')
ax_count.set_yticks(y_locs)
ax_count.set_yticklabels(df_summary['team'] + ' VS ' + df_summary['opp_team'])
ax_count.set_title('Total No. of Match Ups')
ax_count.set_xticks([])
for loc in ['top','left','right','bottom']:
ax_count.spines[loc].set_visible(False)
for p in ax_count.patches:
ax_count.annotate(f'{p.get_width()}',
(p.get_x() + p.get_width(), p.get_y() + p.get_height()/2.),
ha='right', va='center', xytext=(-5,0), textcoords='offset points',
color='white',fontweight='heavy')
ax_win.barh(y_locs, width=df_summary['team_winrate'], color='tab:blue')
ax_win2 = ax_win.twinx()
ax_win2.barh(y_locs, width=df_summary['opp_team_winrate'],
left=df_summary['team_winrate'], color='tab:red')
ax_win.set_yticks(y_locs)
ax_win.set_yticklabels(df_summary['team'])
ax_win2.set_yticks(y_locs)
ax_win2.set_yticklabels(df_summary['opp_team'])
ax_win.set_xlim(0,1)
ax_win.set_title('Winning Rate')
ax_win.set_xticks([])
for loc in ['top','left','right','bottom']:
ax_win.spines[loc].set_visible(False)
ax_win2.spines[loc].set_visible(False)
for p in ax_win.patches:
ax_win.annotate(f'{p.get_width() * 100 :.0f} %',
(0, p.get_y() + p.get_height()/2.),
ha='left', va='center', xytext=(10,0), textcoords='offset points',
color='white',fontweight='heavy')
ax_win2.annotate(f'{(1 - p.get_width()) * 100 :.0f} %',
(1, p.get_y() + p.get_height()/2.),
ha='right', va='center', xytext=(-10,0), textcoords='offset points',
color='white',fontweight='heavy')
plt.show()
推荐阅读
- java - 在多个帧之间传递变量
- wordpress - `woocommerce_save_product_variation` 动作挂钩之前的哪个动作?
- asynchronous - 无法加载类型“System.Diagnostics.DebuggerStepThroughAttribute”
- prolog - 如何在重复中累积(永远)
- tensorflow - 矩阵wrt矩阵的TensorFlow梯度没有意义
- mongodb - MongoDB 中的 $unwind,$project 运算符是什么?
- angular - Angular - 具有来自另一个控件的 valueChanges 的异步验证器
- java - 如何在Java中允许越界索引
- docker - 使用驱动程序 NAT 的 Docker 主机名和其他容器解析
- java - 如何在具有 HTML 内容类型的 JTextPane 上设置固定宽度但动态高度?