首先,您应该通过以下方式重新塑造您的数据框:
df = df.groupby(by = ['opening_shortname', 'winner']).size().reset_index().rename(columns = {'opening_shortname': 'opening_shortname', 'winner': 'winner', 0: 'count'}).sort_values(['count', 'opening_shortname', 'winner'], ascending = False, ignore_index = True)
所以你会得到一个类似(假数据)的数据框:
opening_shortname winner count
0 Queen's Pawn Game White 141
1 Queen's Pawn Game Black 132
2 Queen's Pawn White 57
3 Queen's Pawn Black 57
4 King's Pawn Game Black 57
5 Dutch Defense Black 53
6 Sicilian Defense White 51
7 Sicilian Defense Black 50
8 Nimzowitsch Defense White 46
9 Nimzowitsch Defense Black 45
10 Philidor Defense Black 44
11 Slav Defense White 43
12 Pirc Defense White 42
13 Slav Defense Black 39
14 Pirc Defense Black 38
15 King's Pawn Game White 38
16 Dutch Defense White 36
17 Philidor Defense White 31
然后你可以绘制你的数据,例如使用seaborn.barplot:
sns.barplot(ax = ax, data = df, x = 'count', y = 'opening_shortname', hue = 'winner', palette = ['white', 'black'], edgecolor = 'black')
完整代码
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv(r'data/data.csv')
df = df.groupby(by = ['opening_shortname', 'winner']).size().reset_index().rename(columns = {'opening_shortname': 'opening_shortname', 'winner': 'winner', 0: 'count'}).sort_values(['count', 'opening_shortname', 'winner'], ascending = False, ignore_index = True)
fig, ax = plt.subplots()
sns.barplot(ax = ax, data = df, x = 'count', y = 'opening_shortname', hue = 'winner', palette = ['white', 'black'], edgecolor = 'black')
plt.show()
如果你想绘制相对比例来代替count,那么你可以在上面的代码中添加一行:
df['count'] = df['count']/df.groupby('opening_shortname')['count'].transform('sum')
完整代码
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv(r'data/data.csv')
df = df.groupby(by = ['opening_shortname', 'winner']).size().reset_index().rename(columns = {'opening_shortname': 'opening_shortname', 'winner': 'winner', 0: 'count'}).sort_values(['count', 'opening_shortname', 'winner'], ascending = False, ignore_index = True)
df['count'] = df['count']/df.groupby('opening_shortname')['count'].transform('sum')
fig, ax = plt.subplots()
sns.barplot(ax = ax, data = df, x = 'count', y = 'opening_shortname', hue = 'winner', palette = ['white', 'black'], edgecolor = 'black')
plt.show()