-
Notifications
You must be signed in to change notification settings - Fork 1
/
plots.py
285 lines (233 loc) · 9.14 KB
/
plots.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
import matplotlib
matplotlib.use("Agg") # fix for running on machine without display
import matplotlib.ticker as ticker
import pandas as pd
from datetime import datetime, timedelta
from matplotlib import pyplot as plt
from configparser import ConfigParser
import os
from calculations import get_standings, get_current_track_data, get_individual_records, drop_inactive_players
from utils import get_player_name
import warnings
warnings.filterwarnings("ignore", category=UserWarning) # warning with tight layout
config = ConfigParser()
config.read("config.ini")
def get_total_standings_plot():
path = os.path.join(
config.get("LOCAL_STORAGE", "dir"),
config.get("LOCAL_STORAGE", "total_standings"),
)
return open(path, "rb")
def plot_total_standings(data, to_file=True, backup_name=None, drop_inactive=True):
if drop_inactive:
data = drop_inactive_players(data)
width = data["track_id"].nunique() + 3
height = data["Player"].nunique()
fig, ax = plt.subplots(figsize=(width, height))
# arrange players by total standings
season_standings = get_standings(data)
bar_alignment = pd.Series({p:timedelta(0) for p in season_standings.index}, name="Time")
for track, track_data in data.groupby("track_id", sort=False):
# order subset by total times
track_data = track_data.set_index("Player").loc[season_standings.index]
# general track info
trackname = track_data["Track"].iloc[0]
nadeo = track_data["author"].iloc[0] == "Nadeo" # check if authoer is Nadeo track
# colored barplots for each player
bars = ax.barh(y = track_data.index,
width = track_data["Time"].apply(timedelta.total_seconds),
left = bar_alignment.apply(timedelta.total_seconds),
color = trackname_to_color(trackname, nadeo),
edgecolor = fig.patch.get_facecolor())
# adding up times of plotted track times for following bar plots alignment
bar_alignment += track_data["Time"]
# labeling bars with time information
for i, bar in enumerate(bars):
if track_data["Origin"][i] == "Player":
label = timedelta_to_string(track_data["Time"][i])
else: # no time was set by player
label = track_data["Origin"][i] # label with medal name
ax.text(y = bar.get_y() + bar.get_height()/2,
x = bar.get_x() + bar.get_width()/2 ,
s = label,
horizontalalignment = "center",
verticalalignment = "center",
color = fig.patch.get_facecolor(),
)
# labeling column of bars with track name
ax.text(
y = bar.get_y() + bar.get_height()*1.5,
x = bar.get_x() + bar.get_width()/2,
s = "\n".join(trackname.split("-")), # make - to linebreak
color = trackname_to_color(trackname, nadeo),
verticalalignment = "center",
horizontalalignment = "center",
)
# plot differences in total time
for i, bar in enumerate(bars):
ax.text(
y = bar.get_y() + bar.get_height()/2,
x = bar.get_x() + bar.get_width(),
s = timedelta_to_string(season_standings.diff(-1)[i], add_plus=True),
color = "grey",
verticalalignment = "center",
horizontalalignment = "left",
)
# axis decorating
plt.yticks(
track_data.index,
track_data.reset_index().iloc[::-1].index.map(lambda x: f"{x+1}) ") + track_data.index.map(get_player_name),
horizontalalignment = "left",
)
ax.set_xlabel("Total Time")
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
# y axis tick label alignment
plt.draw() # this is needed because get_window_extent needs a renderer to work
yax = ax.get_yaxis()
pad = max(tick.label.get_window_extent().width for tick in yax.majorTicks)
yax.set_tick_params(pad=pad)
# x tick labels
max_time = season_standings.max().total_seconds()
if max_time > 2*60:
major_ticks = 60
minor_ticks = 15
elif max_time > 60:
major_ticks = 30
minor_ticks = 10
elif max_time > 30:
major_ticks = 15
minor_ticks = 5
else:
major_ticks = 10
minor_ticks = 1
ax.xaxis.set_major_locator(ticker.MultipleLocator(major_ticks))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(minor_ticks))
ax.xaxis.set_major_formatter(timedelta_formatter)
fig.tight_layout()
# save & close
if not backup_name == None:
fig.savefig(
os.path.join(config.get("LOCAL_STORAGE", "dir"), f"{backup_name}.pdf"),
bbox_inches = "tight",
)
if to_file:
fig.savefig(
os.path.join(
config.get("LOCAL_STORAGE", "dir"),
config.get("LOCAL_STORAGE", "total_standings")
),
dpi = 225,
transparent = True,
bbox_inches = "tight",
pad_inches = 0,
)
plt.close(fig)
else:
return plt.gca()
@ticker.FuncFormatter
def timedelta_formatter(x, pos):
string = timedelta_to_string(timedelta(seconds=x)).split(".")[0]
if len(string) == 2:
string = f"00:{string}"
return string
def timedelta_to_string(td, add_plus=False):
if not isinstance(td, timedelta):
return ""
hours = int(td.seconds//3600)
minutes = int(td.seconds//60%60)
seconds = int(td.seconds-hours*3600-minutes*60)
centiseconds = int(td.microseconds/10**4)
if hours > 0:
string = f"{hours}:{minutes}:{seconds}.{centiseconds}"
elif minutes > 0:
string = f"{minutes}:{seconds}.{centiseconds}"
else:
string = f"{seconds}.{centiseconds}"
digits = string.split(":")
digits = ["0" + d if len(d.split(".")[0])==1 else d for d in digits]
string = ":".join(digits)
pre, centi = string.split(".")
if len(centi) == 1:
centi = "0" + centi
string = f"{pre}.{centi}"
if add_plus:
string = "+" + string
return string
def track_standings_to_color(track_data):
mapping = {
0: "gold",
1: "silver",
2: "goldenrod",
}
track_standings = get_standings(track_data)[::-1].reset_index()
track_standings_index = [track_standings[track_standings["Player"] == player].index[0] for player in track_data.index]
return [mapping[index] if index in mapping.keys() else "white" for index in track_standings_index]
def trackname_to_color(trackname="", nadeo=True):
mapping = {
"A": "#c1c1c1",
"B": "#1fa11f",
"C": "#107df7",
"D": "#fa2e12",
"E": "#181818",
}
if nadeo:
try:
return mapping[trackname[0]]
except KeyError or IndexError: pass
return "orange"
def get_ladder(flavor="current"):
assert flavor in ["current", "total"]
path = os.path.join(
config.get("LOCAL_STORAGE", "dir"),
flavor + "-" + config.get("LOCAL_STORAGE", "ladder"),
)
with open(path, "r") as file:
return file.read()
def print_current_ladder(data, style="html"):
data = get_current_track_data(data)
data = data[data["Origin"] == "Player"]
ladder = get_individual_records(data).sort_values(["Time", "Date"], ascending=[False, False]).set_index("Player")["Time"]
if style == "html":
content = ladder_as_html(ladder, data["Track"].unique()[0])
elif style == "md":
content = ladder_as_md(ladder)
path = os.path.join(
config.get("LOCAL_STORAGE", "dir"),
"current-" + config.get("LOCAL_STORAGE", "ladder"),
)
with open(path, "w") as file:
file.write(content)
def print_total_ladder(data, style="html"):
data = get_individual_records(data)
ladder = data.groupby("Player")["Time"].sum().sort_values(ascending=False)
if style == "html":
content = ladder_as_html(ladder, "Season Leaderboard")
elif style == "md":
content = ladder_as_md(ladder)
path = os.path.join(
config.get("LOCAL_STORAGE", "dir"),
"total-" + config.get("LOCAL_STORAGE", "ladder"),
)
with open(path, "w") as file:
file.write(content)
def ladder_as_md(ladder):
md = "P | Name | Time\n" # title
md += ":---:|:--- | ---:\n" # alignment
for i, player in enumerate(list(reversed(ladder.index))):
md += f"{i+1} | {get_player_name(player)} | {timedelta_to_string(ladder[player])}\n"
return md
def ladder_as_html(ladder, title):
lines = [title]
for i, player in enumerate(list(reversed(ladder.index))):
line = f"{i+1}) {get_player_name(player)}~ {timedelta_to_string(ladder[player])} "
lines.append(line)
max_linelength = max([len(line) for line in lines])
missing_spaces = [(max_linelength-len(line)) for line in lines]
lines = [(spaces*" ").join(line.split("~")) for spaces, line in zip(missing_spaces, lines)]
message = "\n".join(lines)
return f"<pre>{message}</pre>"
if __name__ == "__main__":
from calculations import calculate_complete_data
data = calculate_complete_data()
plot_total_standings(data)