-
Notifications
You must be signed in to change notification settings - Fork 12
/
olympicdash-py-3.qmd
440 lines (349 loc) · 13.5 KB
/
olympicdash-py-3.qmd
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
---
title: "Olympic Games"
format:
dashboard:
orientation: columns
nav-buttons: [github]
github: https://github.com/posit-conf-2024/olympicdash
logo: images/olympics-logo.svg
logo-alt: "Olympics logo with multicolored circles."
---
```{python}
#| label: load-packages
from plotnine import *
import great_tables as gt
import pandas as pd
```
```{python}
#| label: load-data
olympics_full = pd.read_csv("data/olympics.csv", low_memory = False)
```
```{python}
#| label: prep-data
# Filter for non-NA medals
olympics = olympics_full[(olympics_full["medal"].notna())]
# Split the team column at "-" into two columns
split_data = olympics["team"].str.split("-", n = 1, expand = True)
olympics.loc[:, "team"] = split_data[0]
# Reorder the medal column categories
olympics["medal"] = pd.Categorical(olympics["medal"], categories = ["Bronze", "Silver", "Gold"])
```
# 🌞 Summer Olympics
```{python}
#| label: summmer-prep-data
summer_olympics = olympics[(olympics["season"] == "Summer")]
summer_olympics.reset_index(drop=True, inplace=True)
```
## Column - Medals by sport and year {width=65%}
### Row - Medals by sport {height=60%}
```{python}
#| label: summer-medals-by-sport
#| title: Medals by sport
# Lump the sport column to top 15 categories, grouping others as Other
top_15_sports = summer_olympics["sport"].value_counts().nlargest(15).index
summer_olympics["sport"] = summer_olympics["sport"].apply(lambda x: x if x in top_15_sports else "Other")
# Convert the sport column to a categorical type with order based on frequency, and reverse the order
summer_olympics["sport"] = pd.Categorical(summer_olympics["sport"], categories = summer_olympics["sport"].value_counts().index[::-1])
# Move the Other category of the sport column to the beginning
new_order = ["Other"] + [cat for cat in summer_olympics["sport"].cat.categories if cat != "Other"]
summer_olympics["sport"] = summer_olympics["sport"].cat.reorder_categories(new_order)
# Plot
(
ggplot(summer_olympics, aes(x = "sport", fill = "medal")) +
geom_bar() +
coord_flip() +
guides(fill = guide_legend(reverse = True)) +
labs(
x = "",
y = "",
fill = "Medal"
) +
theme_minimal() +
theme(
legend_position = "inside",
legend_position_inside = (0.9, 0.2),
legend_direction = "horizontal",
legend_background = element_rect(fill = "white", color = "gray"),
figure_size = (10, 6.18)
)
)
```
### Row - Medals by year {height=40%}
::: {.card title="Medals by year"}
Due to World War II, no olympic games were held in 1940 and 1944.
```{python}
#| label: summer-medals-by-year
#| title: Medals by year
# Count the occurrences of each medal per year
summer_olympics_count = summer_olympics.groupby(["year", "medal"], observed=True).size().reset_index(name = "n")
# Plot
(
ggplot(summer_olympics_count, aes(x = "year", y = "n", color = "medal")) +
geom_point(size = 0.5) +
geom_line() +
guides(color = guide_legend(reverse = True)) +
scale_x_continuous(breaks = range(1896, 2020, 8)) +
labs(x = "Year", y = "", color = "Medal") +
theme_minimal() +
theme(
legend_position = "inside",
legend_position_inside = (0.9, 0.2),
legend_direction = "horizontal",
legend_background = element_rect(fill = "white", color = "gray"),
figure_size = (10, 3)
)
)
```
:::
## Column - Medals by country {width=35%}
### Row - Value boxes {height=30%}
```{python}
#| label: summer-calculate-most-medals
# Filter for gold medals
gold_medals = summer_olympics[summer_olympics['medal'] == 'Gold']
# Group by team and count gold medals
gold_medal_counts = gold_medals.groupby('team').size()
# Find the team with the most gold medals
most_gold_medals = gold_medal_counts.idxmax()
count_most_gold_medals = gold_medal_counts.max()
# Filter for silver medals
silver_medals = summer_olympics[summer_olympics['medal'] == 'Silver']
# Group by team and count silver medals
silver_medal_counts = silver_medals.groupby('team').size()
# Find the team with the most silver medals
most_silver_medals = silver_medal_counts.idxmax()
count_most_silver_medals = silver_medal_counts.max()
# Filter for bronze medals
bronze_medals = summer_olympics[summer_olympics['medal'] == 'Bronze']
# Group by team and count bronze medals
bronze_medal_counts = bronze_medals.groupby('team').size()
# Find the team with the most bronze medals
most_bronze_medals = bronze_medal_counts.idxmax()
count_most_bronze_medals = bronze_medal_counts.max()
```
::: {.valuebox icon="award-fill" color="#d4af37"}
Most golds:
`{python} str(count_most_gold_medals)`
`{python} most_gold_medals`
:::
::: {.valuebox icon="award-fill" color="#c0c0c0"}
Most silvers:
`{python} str(count_most_silver_medals)`
`{python} most_silver_medals`
:::
::: {.valuebox icon="award-fill" color="#cd7f32"}
Most bronzes:
`{python} str(count_most_bronze_medals)`
`{python} most_bronze_medals`
:::
### Row - Tabsets of tables {height=70% .tabset}
```{python}
#| label: summer-medals-by-country
#| title: Medals by country
# Count the occurrences of each medal per team
summer_olympics_count = summer_olympics.groupby(["team", "medal"]).size().reset_index(name="n")
# Pivot olympics_count to get medals as columns
summer_olympics_pivot = summer_olympics_count.pivot_table(index = "team", columns = "medal", values = "n", fill_value = 0)
# Calculate the total number of medals
summer_olympics_pivot["Total"] = summer_olympics_pivot[["Bronze", "Gold", "Silver"]].sum(axis=1)
# Reset the index and rearrange columns
summer_olympics_pivot = summer_olympics_pivot.reset_index()
summer_olympics_pivot = summer_olympics_pivot[["team", "Gold", "Silver", "Bronze", "Total"]]
# Sort by Total medals, then team
summer_olympics_sorted_descending = summer_olympics_pivot.sort_values(by=["Total", "team"], ascending=[False, True])
summer_olympics_sorted_ascending = summer_olympics_pivot.sort_values(by=["Total", "team"], ascending=[True, True])
# Remove Total
summer_olympics_sorted_descending = summer_olympics_sorted_descending[["team", "Gold", "Silver", "Bronze"]]
summer_olympics_sorted_ascending = summer_olympics_sorted_ascending[["team", "Gold", "Silver", "Bronze"]]
# Rename the team column to Team
summer_olympics_sorted_descending.rename(columns={"team": "Team"}, inplace=True)
summer_olympics_sorted_ascending.rename(columns={"team": "Team"}, inplace=True)
# Find top and bottom 30
summer_olympics_sorted_descending_top30 = summer_olympics_sorted_descending.head(30)
summer_olympics_sorted_descending_top30.reset_index(drop=True, inplace=True)
summer_olympics_sorted_ascending_bottom30 = summer_olympics_sorted_ascending.head(30)
summer_olympics_sorted_ascending_bottom30.reset_index(drop=True, inplace=True)
```
::: {.card title="Top 30 total medals"}
Teams sorted in descending order of total medals.
```{python}
#| label: summer-top-30-medals
(
gt.GT(summer_olympics_sorted_descending_top30).data_color(
columns=["Gold", "Silver", "Bronze"],
palette="Oranges"
)
)
```
:::
::: {.card title="Bottom 30 total medals"}
Teams sorted in ascending order of total medals.
```{python}
#| label: summer-bottom-30-medals
(
gt.GT(summer_olympics_sorted_ascending_bottom30).data_color(
columns=["Gold", "Silver", "Bronze"],
palette="Blues"
)
)
```
:::
# ❄️ Winter Olympics
```{python}
#| label: winter-prep-data
winter_olympics = olympics[(olympics["season"] == "Winter")]
winter_olympics.reset_index(drop=True, inplace=True)
```
## Column - Medals by sport and year {width=65%}
### Row - Medals by sport {height=60%}
```{python}
#| label: winter-medals-by-sport
#| title: Medals by sport
# Lump the sport column to top 15 categories, grouping others as Other
top_15_sports = winter_olympics["sport"].value_counts().nlargest(15).index
winter_olympics["sport"] = winter_olympics["sport"].apply(lambda x: x if x in top_15_sports else "Other")
# Convert the sport column to a categorical type with order based on frequency, and reverse the order
winter_olympics["sport"] = pd.Categorical(winter_olympics["sport"], categories = winter_olympics["sport"].value_counts().index[::-1])
# Move the Other category of the sport column to the beginning
new_order = ["Other"] + [cat for cat in winter_olympics["sport"].cat.categories if cat != "Other"]
winter_olympics["sport"] = winter_olympics["sport"].cat.reorder_categories(new_order)
# Plot
(
ggplot(winter_olympics, aes(x = "sport", fill = "medal")) +
geom_bar() +
coord_flip() +
guides(fill = guide_legend(reverse = True)) +
labs(
x = "",
y = "",
fill = "Medal"
) +
theme_minimal() +
theme(
legend_position = "inside",
legend_position_inside = (0.9, 0.2),
legend_direction = "horizontal",
legend_background = element_rect(fill = "white", color = "gray"),
figure_size = (10, 6.18)
)
)
```
### Row - Medals by year {height=40%}
::: {.card title="Medals by year"}
Due to World War II, no olympic games were held in 1940 and 1944.
```{python}
#| label: winter-medals-by-year
# Count the occurrences of each medal per year
winter_olympics_count = winter_olympics.groupby(["year", "medal"], observed=True).size().reset_index(name = "n")
# Plot
(
ggplot(winter_olympics_count, aes(x = "year", y = "n", color = "medal")) +
geom_point(size = 0.5) +
geom_line() +
guides(color = guide_legend(reverse = True)) +
scale_x_continuous(breaks = range(1896, 2020, 8)) +
labs(x = "Year", y = "", color = "Medal") +
theme_minimal() +
theme(
legend_position = "inside",
legend_position_inside = (0.9, 0.2),
legend_direction = "horizontal",
legend_background = element_rect(fill = "white", color = "gray"),
figure_size = (10, 3)
)
)
```
:::
## Column - Medals by country {width=35%}
### Row - Value boxes {height=30%}
```{python}
#| label: winter-calculate-most-medals
# Filter for gold medals
gold_medals = winter_olympics[winter_olympics['medal'] == 'Gold']
# Group by team and count gold medals
gold_medal_counts = gold_medals.groupby('team').size()
# Find the team with the most gold medals
most_gold_medals = gold_medal_counts.idxmax()
count_most_gold_medals = gold_medal_counts.max()
# Filter for silver medals
silver_medals = winter_olympics[winter_olympics['medal'] == 'Silver']
# Group by team and count silver medals
silver_medal_counts = silver_medals.groupby('team').size()
# Find the team with the most silver medals
most_silver_medals = silver_medal_counts.idxmax()
count_most_silver_medals = silver_medal_counts.max()
# Filter for bronze medals
bronze_medals = winter_olympics[winter_olympics['medal'] == 'Bronze']
# Group by team and count bronze medals
bronze_medal_counts = bronze_medals.groupby('team').size()
# Find the team with the most bronze medals
most_bronze_medals = bronze_medal_counts.idxmax()
count_most_bronze_medals = bronze_medal_counts.max()
```
::: {.valuebox icon="award-fill" color="#d4af37"}
Most golds:
`{python} str(count_most_gold_medals)`
`{python} most_gold_medals`
:::
::: {.valuebox icon="award-fill" color="#c0c0c0"}
Most silvers:
`{python} str(count_most_silver_medals)`
`{python} most_silver_medals`
:::
::: {.valuebox icon="award-fill" color="#cd7f32"}
Most bronzes:
`{python} str(count_most_bronze_medals)`
`{python} most_bronze_medals`
:::
### Row - Tabsets of tables {height=70% .tabset}
```{python}
#| label: winter-medals-by-country
#| title: Medals by country
# Count the occurrences of each medal per team
winter_olympics_count = winter_olympics.groupby(["team", "medal"]).size().reset_index(name="n")
# Pivot olympics_count to get medals as columns
winter_olympics_pivot = winter_olympics_count.pivot_table(index = "team", columns = "medal", values = "n", fill_value = 0)
# Calculate the total number of medals
winter_olympics_pivot["Total"] = winter_olympics_pivot[["Bronze", "Gold", "Silver"]].sum(axis=1)
# Reset the index and rearrange columns
winter_olympics_pivot = winter_olympics_pivot.reset_index()
winter_olympics_pivot = winter_olympics_pivot[["team", "Gold", "Silver", "Bronze", "Total"]]
# Sort by Total medals, then team
winter_olympics_sorted_descending = winter_olympics_pivot.sort_values(by=["Total", "team"], ascending=[False, True])
winter_olympics_sorted_ascending = winter_olympics_pivot.sort_values(by=["Total", "team"], ascending=[True, True])
# Remove Total
winter_olympics_sorted_descending = winter_olympics_sorted_descending[["team", "Gold", "Silver", "Bronze"]]
winter_olympics_sorted_ascending = winter_olympics_sorted_ascending[["team", "Gold", "Silver", "Bronze"]]
# Rename the team column to Team
winter_olympics_sorted_descending.rename(columns={"team": "Team"}, inplace=True)
winter_olympics_sorted_ascending.rename(columns={"team": "Team"}, inplace=True)
# Find top and bottom 30
winter_olympics_sorted_descending_top30 = winter_olympics_sorted_descending.head(30)
winter_olympics_sorted_descending_top30.reset_index(drop=True, inplace=True)
winter_olympics_sorted_ascending_bottom30 = winter_olympics_sorted_ascending.head(30)
winter_olympics_sorted_ascending_bottom30.reset_index(drop=True, inplace=True)
```
::: {.card title="Top 30 total medals"}
Teams sorted in descending order of total medals.
```{python}
#| label: winter-top-30-medals
(
gt.GT(winter_olympics_sorted_descending_top30).data_color(
columns=["Gold", "Silver", "Bronze"],
palette="Oranges"
)
)
```
:::
::: {.card title="Bottom 30 total medals"}
Teams sorted in ascending order of total medals.
```{python}
#| label: winter-bottom-30-medals
(
gt.GT(winter_olympics_sorted_ascending_bottom30).data_color(
columns=["Gold", "Silver", "Bronze"],
palette="Blues"
)
)
```
:::