Agregasi dan Visualisasi Tranfermarkt

library(mongolite)
Warning: package 'mongolite' was built under R version 4.4.3
library(dplyr)

Attaching package: 'dplyr'
The following objects are masked from 'package:stats':

    filter, lag
The following objects are masked from 'package:base':

    intersect, setdiff, setequal, union
library(ggplot2)
library(jsonlite)
Warning: package 'jsonlite' was built under R version 4.4.2
library(ggflags)
library(ggimage)
Warning: package 'ggimage' was built under R version 4.4.3

Attaching package: 'ggimage'
The following object is masked from 'package:ggflags':

    geom_flag
library(rnaturalearth)
Warning: package 'rnaturalearth' was built under R version 4.4.3
library(rnaturalearthdata)
Warning: package 'rnaturalearthdata' was built under R version 4.4.3

Attaching package: 'rnaturalearthdata'
The following object is masked from 'package:rnaturalearth':

    countries110
library(sf)
Linking to GEOS 3.12.1, GDAL 3.8.4, PROJ 9.3.1; sf_use_s2() is TRUE
library(countrycode)
Warning: package 'countrycode' was built under R version 4.4.3
library(png)
library(grid)
library(cowplot)

Attaching package: 'cowplot'
The following object is masked from 'package:ggimage':

    theme_nothing
library(scales)
library(lubridate)

Attaching package: 'lubridate'
The following object is masked from 'package:cowplot':

    stamp
The following objects are masked from 'package:base':

    date, intersect, setdiff, union
library(tidyr)
library(magrittr)

Attaching package: 'magrittr'
The following object is masked from 'package:tidyr':

    extract
library(forcats)
# KONEKSI
conn <- mongo(
  collection = "Player",
  db = "EPl_Player",
  url = "mongodb+srv://panjiarf:Jambi0412@cluster0.cghdizu.mongodb.net/")

Agregasi pemain

#Asal Negara Pemain EPL
query_country <- '[
  { "$project": { "_id": 0, "country": { "$arrayElemAt": [ "$profile.citizenship", 0 ] } } },
  { "$group": { "_id": "$country", "total_players": { "$sum": 1 } } },
  { "$sort": { "total_players": -1 } }
]'
result_country <- conn$aggregate(query_country)
colnames(result_country) <- c("country", "total_players")
print(head(result_country))
      country total_players
1     England           177
2      Brazil            33
3      France            26
4 Netherlands            21
5       Spain            20
6    Portugal            19
top10_country <- result_country %>% slice_max(total_players, n = 10)
print(top10_country)
       country total_players
1      England           177
2       Brazil            33
3       France            26
4  Netherlands            21
5        Spain            20
6     Portugal            19
7      Denmark            17
8      Ireland            16
9    Argentina            14
10     Germany            12
11    Scotland            12
#Usia berdasarkan posisi pemain
query_age_pos <- '[
  { "$group": {
      "_id": { "age": "$profile.age", "position": "$profile.position.main" },
      "total_players": { "$sum": 1 }
    }
  },
  { "$sort": { "_id.age": 1, "total_players": -1 } }
]'
result_age_pos <- conn$aggregate(query_age_pos)
result_age_pos <- result_age_pos %>% tidyr::unnest_wider(`_id`) %>% rename(age = age, position = position)
print((result_age_pos))
# A tibble: 179 × 3
     age position         total_players
   <int> <chr>                    <int>
 1    17 Centre-Forward               1
 2    17 Left Winger                  1
 3    18 Right-Back                   3
 4    18 Centre-Back                  3
 5    18 Left-Back                    2
 6    18 Central Midfield             2
 7    18 Centre-Forward               1
 8    18 Right Winger                 1
 9    19 Centre-Back                  3
10    19 Central Midfield             3
# ℹ 169 more rows
#Top 5 market value tertinggi
query_max_value <- '[
  { "$match": { "profile.marketValue": { "$gt": 0 } } },
  { "$project": {
      "_id": 0,
      "name": "$profile.name",
      "club": "$profile.club.name",
      "position": "$profile.position.main",
      "market_value": "$profile.marketValue",
      "image": "$profile.imageUrl"
    }
  },
  { "$sort": { "market_value": -1 } },
  { "$limit": 5 }
]'
result_max_value <- conn$aggregate(query_max_value)
result_max_value$market_value <- as.numeric(result_max_value$market_value)
print(result_max_value)
            name     club           position market_value
1 Erling Haaland Man City     Centre-Forward      2.0e+08
2    Bukayo Saka  Arsenal       Right Winger      1.5e+08
3    Cole Palmer  Chelsea Attacking Midfield      1.3e+08
4          Rodri Man City Defensive Midfield      1.3e+08
5     Phil Foden Man City       Right Winger      1.3e+08
                                                                              image
1 https://img.a.transfermarkt.technology/portrait/header/418560-1709108116.png?lm=1
2 https://img.a.transfermarkt.technology/portrait/header/433177-1684155052.jpg?lm=1
3 https://img.a.transfermarkt.technology/portrait/header/568177-1712320986.jpg?lm=1
4 https://img.a.transfermarkt.technology/portrait/header/357565-1682587890.jpg?lm=1
5 https://img.a.transfermarkt.technology/portrait/header/406635-1668524492.jpg?lm=1
#Top 5 market value terendah
query_min_value <- '[
  { "$match": { "profile.marketValue": { "$gt": 0 } } },
  { "$project": {
      "_id": 0,
      "name": "$profile.name",
      "club": "$profile.club.name",
      "position": "$profile.position.main",
      "market_value": "$profile.marketValue",
      "image": "$profile.imageUrl"
    }
  },
  { "$sort": { "market_value": 1 } },
  { "$limit": 5 }
]'
result_min_value <- conn$aggregate(query_min_value)
result_min_value$market_value <- as.numeric(result_min_value$market_value)
print(result_min_value)
             name           club           position market_value
1 Wayne Hennessey   Nottm Forest         Goalkeeper       175000
2      John Ruddy      Newcastle         Goalkeeper       200000
3        Tom King         Wolves         Goalkeeper       200000
4    Kaden Rodney Crystal Palace Defensive Midfield       200000
5    Scott Carson       Man City         Goalkeeper       200000
                                                                              image
1  https://img.a.transfermarkt.technology/portrait/header/45494-1668070425.jpg?lm=1
2  https://img.a.transfermarkt.technology/portrait/header/29712-1736421115.jpg?lm=1
3 https://img.a.transfermarkt.technology/portrait/header/215810-1621592912.jpg?lm=1
4 https://img.a.transfermarkt.technology/portrait/header/860078-1737712510.jpg?lm=1
5  https://img.a.transfermarkt.technology/portrait/header/14555-1666733622.jpg?lm=1
#history 5 pemain market value tertinggi dalam 5 tahun terakhir
top5_names <- result_max_value$name
top5_json <- paste0('["', paste(top5_names, collapse = '","'), '"]')

query_history <- sprintf('[
  { "$match": { "profile.name": { "$in": %s } } },
  { "$project": {
      "name": "$profile.name",
      "history": "$market_value.marketValueHistory"
    }
  },
  { "$unwind": "$history" },
  { "$project": {
      "_id": 0,
      "name": 1,
      "date": "$history.date",
      "market_value": "$history.marketValue"
    }
  }
]', top5_json)

result_history <- conn$aggregate(query_history)
result_history$market_value <- as.numeric(result_history$market_value)
result_history$date <- as.Date(result_history$date)
result_history <- result_history %>%
  filter(date >= Sys.Date() - years(5))
print(result_history)
             name       date market_value
1           Rodri 2020-10-13      6.4e+07
2           Rodri 2021-03-18      7.0e+07
3           Rodri 2021-05-31      7.0e+07
4           Rodri 2021-12-23      7.0e+07
5           Rodri 2022-06-15      8.0e+07
6           Rodri 2022-11-03      8.0e+07
7           Rodri 2023-06-20      9.0e+07
8           Rodri 2023-10-09      1.0e+08
9           Rodri 2023-12-19      1.1e+08
10          Rodri 2024-05-27      1.2e+08
11          Rodri 2024-07-18      1.3e+08
12          Rodri 2024-12-16      1.3e+08
13     Phil Foden 2020-07-30      4.0e+07
14     Phil Foden 2020-10-13      6.0e+07
15     Phil Foden 2021-03-18      7.0e+07
16     Phil Foden 2021-05-28      8.0e+07
17     Phil Foden 2021-12-23      8.5e+07
18     Phil Foden 2022-03-29      9.0e+07
19     Phil Foden 2022-06-15      9.0e+07
20     Phil Foden 2022-11-03      1.1e+08
21     Phil Foden 2023-06-20      1.1e+08
22     Phil Foden 2023-12-19      1.1e+08
23     Phil Foden 2024-03-14      1.3e+08
24     Phil Foden 2024-05-27      1.5e+08
25     Phil Foden 2024-12-16      1.4e+08
26     Phil Foden 2025-03-18      1.3e+08
27 Erling Haaland 2020-09-16      8.0e+07
28 Erling Haaland 2020-11-26      1.0e+08
29 Erling Haaland 2021-02-10      1.1e+08
30 Erling Haaland 2021-06-09      1.3e+08
31 Erling Haaland 2021-10-07      1.5e+08
32 Erling Haaland 2021-12-22      1.5e+08
33 Erling Haaland 2022-06-09      1.5e+08
34 Erling Haaland 2022-11-03      1.7e+08
35 Erling Haaland 2023-06-20      1.8e+08
36 Erling Haaland 2023-12-19      1.8e+08
37 Erling Haaland 2024-05-27      1.8e+08
38 Erling Haaland 2024-10-01      2.0e+08
39 Erling Haaland 2024-12-16      2.0e+08
40    Bukayo Saka 2020-07-30      3.5e+07
41    Bukayo Saka 2020-10-13      4.0e+07
42    Bukayo Saka 2021-03-18      6.0e+07
43    Bukayo Saka 2021-05-28      6.5e+07
44    Bukayo Saka 2021-12-23      6.5e+07
45    Bukayo Saka 2022-06-15      6.5e+07
46    Bukayo Saka 2022-09-15      7.0e+07
47    Bukayo Saka 2022-11-03      9.0e+07
48    Bukayo Saka 2022-12-23      1.0e+08
49    Bukayo Saka 2023-03-16      1.1e+08
50    Bukayo Saka 2023-06-20      1.2e+08
51    Bukayo Saka 2023-12-19      1.2e+08
52    Bukayo Saka 2024-03-14      1.3e+08
53    Bukayo Saka 2024-05-27      1.4e+08
54    Bukayo Saka 2024-12-16      1.5e+08
55    Cole Palmer 2021-03-18      5.0e+05
56    Cole Palmer 2021-12-23      3.0e+06
57    Cole Palmer 2022-06-15      6.0e+06
58    Cole Palmer 2022-09-15      1.0e+07
59    Cole Palmer 2022-11-03      1.5e+07
60    Cole Palmer 2023-06-20      1.5e+07
61    Cole Palmer 2023-07-12      1.8e+07
62    Cole Palmer 2023-10-09      3.2e+07
63    Cole Palmer 2023-12-19      4.5e+07
64    Cole Palmer 2024-03-14      5.5e+07
65    Cole Palmer 2024-05-27      8.0e+07
66    Cole Palmer 2024-10-01      9.0e+07
67    Cole Palmer 2024-12-16      1.3e+08
#Toal market value setiap klub
query_market <- '[
  { "$group": {
      "_id": "$profile.club.name",
      "total_market_value": { "$sum": "$profile.marketValue" }
    }
  },
  { "$sort": { "total_market_value": -1 } },
  { "$limit": 10 }
]'
result_market <- conn$aggregate(query_market)
colnames(result_market) <- c("club", "total_market_value")
result_market$total_market_value <- as.numeric(result_market$total_market_value)
print(result_market)
          club total_market_value
1     Man City         1305200000
2      Arsenal         1127000000
3    Liverpool          993500000
4      Chelsea          922000000
5    Tottenham          836100000
6      Man Utd          694250000
7    Newcastle          635000000
8  Aston Villa          627500000
9     Brighton          555600000
10    West Ham          453300000
# Rata-rata market value per posisi 
query_pos <- '[
  { "$group": {
      "_id": "$profile.position.main",
      "avg_value": { "$avg": "$profile.marketValue" },
      "jumlah_pemain": { "$sum": 1 }
    }
  },
  { "$sort": { "avg_value": -1 } }
]'
result_pos <- conn$aggregate(query_pos)
colnames(result_pos) <- c("position", "avg_value", "jumlah_pemain")
result_pos$avg_value <- as.numeric(result_pos$avg_value)
print(result_pos)
             position avg_value jumlah_pemain
1  Attacking Midfield  32860606            33
2        Right Winger  29597619            42
3       Left Midfield  29000000             3
4      Centre-Forward  27533333            58
5  Defensive Midfield  25653191            47
6         Left Winger  25284615            39
7    Central Midfield  22459016            61
8         Centre-Back  21487755            99
9           Left-Back  19126829            42
10         Right-Back  17692000            50
11     Right Midfield   8000000             2
12     Second Striker   8000000             1
13         Goalkeeper   7799621            66
# Pemain dengan Achievement Terbanyak
query_achieve <- '[
  { "$project": {
      "_id": 0,
      "name": "$profile.name",
      "achievements_count": { "$size": "$achievements" },
      "image": "$profile.imageUrl"
    }
  },
  { "$sort": { "achievements_count": -1 } },
  { "$limit": 5 }
]'
result_achieve <- conn$aggregate(query_achieve)
colnames(result_achieve) <- c("name", "jumlah", "image")
result_achieve$label <- paste0("   ", result_achieve$name)
print(result_achieve)
             name jumlah
1 Kevin De Bruyne     15
2  Erling Haaland     14
3   Mohamed Salah     14
4        Casemiro     13
5         Ederson     13
                                                                              image
1  https://img.a.transfermarkt.technology/portrait/header/88755-1713391485.jpg?lm=1
2 https://img.a.transfermarkt.technology/portrait/header/418560-1709108116.png?lm=1
3 https://img.a.transfermarkt.technology/portrait/header/148455-1727337594.jpg?lm=1
4  https://img.a.transfermarkt.technology/portrait/header/16306-1699018876.jpg?lm=1
5 https://img.a.transfermarkt.technology/portrait/header/238223-1713391842.jpg?lm=1
               label
1    Kevin De Bruyne
2     Erling Haaland
3      Mohamed Salah
4           Casemiro
5            Ederson
# Total Tranfer Fee Masuk ke Klub=
query_transfer_fee <- '[
  { "$unwind": "$transfers" },
  { "$match": { "transfers.fee": { "$gt": 0 } } },
  { "$group": {
      "_id": "$transfers.clubTo.name",
      "total_fee": { "$sum": "$transfers.fee" }
    }
  },
  { "$sort": { "total_fee": -1 } },
  { "$limit": 10 }
]'
result_transfers <- conn$aggregate(query_transfer_fee)
colnames(result_transfers) <- c("club_to", "total_fee")
print(result_transfers)
       club_to  total_fee
1      Chelsea 1577900000
2     Man City 1318950000
3      Man Utd  999620000
4      Arsenal  825550000
5    Tottenham  823450000
6    Liverpool  736675000
7    Newcastle  666350000
8       Wolves  556536000
9  Aston Villa  527449999
10    Brighton  493080000
# Top 5 Pemain dengan menit bermain terbanyak=
query_minutes <- '[
  { "$unwind": "$stats" },
  { "$match": {
      "stats.competitionId": "GB1",
      "stats.seasonId": "24/25"
    }
  },
  { "$group": {
      "_id": "$profile.name",
      "total_minutes": { "$sum": "$stats.minutesPlayed" },
      "image": { "$first": "$profile.imageUrl" }
    }
  },
  { "$sort": { "total_minutes": -1 } },
  { "$limit": 5 }
]'

result_minutes <- conn$aggregate(query_minutes)
colnames(result_minutes) <- c("name", "total_minutes", "image")
print(result_minutes)
               name total_minutes
1   Marcus Rashford          1426
2 James Ward-Prowse          1201
3      Julio Enciso          1004
4      Harry Wilson           999
5 Christian Eriksen           992
                                                                              image
1 https://img.a.transfermarkt.technology/portrait/header/258923-1674473054.jpg?lm=1
2 https://img.a.transfermarkt.technology/portrait/header/181579-1684751045.jpg?lm=1
3 https://img.a.transfermarkt.technology/portrait/header/660867-1669388786.jpg?lm=1
4 https://img.a.transfermarkt.technology/portrait/header/279455-1668070758.jpg?lm=1
5  https://img.a.transfermarkt.technology/portrait/header/69633-1718628122.jpg?lm=1
# Top 5 Goal Terbanyak 5 tahun terakhir
query_goals <- '[
  { "$unwind": "$stats" },
  { "$match": {
      "stats.competitionId": "GB1",
      "stats.seasonId": { "$in": ["20/21", "21/22", "22/23", "23/24", "24/25"] }
    }
  },
  { "$group": {
      "_id": "$profile.name",
      "total_goals": { "$sum": "$stats.goals" },
      "image": { "$first": "$profile.imageUrl" }
    }
  },
  { "$sort": { "total_goals": -1 } },
  { "$limit": 5 }
]'
result_goals <- conn$aggregate(query_goals)
colnames(result_goals) <- c("name", "goals", "image")
print(head(result_goals))
            name goals
1  Mohamed Salah   110
2 Erling Haaland    84
3  Ollie Watkins    74
4  Heung-min Son    74
5     Phil Foden    55
                                                                              image
1 https://img.a.transfermarkt.technology/portrait/header/148455-1727337594.jpg?lm=1
2 https://img.a.transfermarkt.technology/portrait/header/418560-1709108116.png?lm=1
3 https://img.a.transfermarkt.technology/portrait/header/324358-1708341279.jpg?lm=1
4  https://img.a.transfermarkt.technology/portrait/header/91845-1669336455.jpg?lm=1
5 https://img.a.transfermarkt.technology/portrait/header/406635-1668524492.jpg?lm=1
# pemain paling sering pindah klub dan total transfer fee
query_transfer_count <- '[
  { "$unwind": "$transfers" },
  { "$match": { "transfers.clubTo.name": { "$ne": null } } },
  { "$group": {
      "_id": "$profile.name",
      "transfer_count": { "$sum": 1 },
      "total_fee": { "$sum": { "$ifNull": ["$transfers.fee", 0] } },
      "image": { "$first": "$profile.imageUrl" }
    }
  },
  { "$sort": { "transfer_count": -1 } }
]'
result_transfer_count <- conn$aggregate(query_transfer_count)
colnames(result_transfer_count) <- c("name", "transfer_count", "total_fee", "image")
print(head(result_transfer_count))
              name transfer_count total_fee
1       John Ruddy             24    975000
2    Sam Johnstone             24  19250000
3    Asmir Begovic             23  26375000
4       Chris Wood             22  72729999
5       Joe Lumley             21         0
6 Christian Walton             21         0
                                                                              image
1  https://img.a.transfermarkt.technology/portrait/header/29712-1736421115.jpg?lm=1
2 https://img.a.transfermarkt.technology/portrait/header/110864-1672915792.jpg?lm=1
3  https://img.a.transfermarkt.technology/portrait/header/33873-1737919950.jpg?lm=1
4 https://img.a.transfermarkt.technology/portrait/header/108725-1740646786.jpg?lm=1
5 https://img.a.transfermarkt.technology/portrait/header/336367-1709158388.jpg?lm=1
6 https://img.a.transfermarkt.technology/portrait/header/208379-1720189930.jpg?lm=1
# pemain dengan yellow card dan red card terbanyak
query_cards <- '[
  { "$unwind": "$stats" },
  { "$group": {
      "_id": "$profile.name",
      "yellow_cards": { "$sum": { "$ifNull": ["$stats.yellowCards", 0] } },
      "red_cards": { "$sum": { "$ifNull": ["$stats.redCards", 0] } },
      "image": { "$first": "$profile.imageUrl" }
    }
  },
  { "$sort": { "yellow_cards": -1, "red_cards": -1 } }
]'
result_cards <- conn$aggregate(query_cards)
colnames(result_cards) <- c("name", "yellow_cards", "red_cards", "image")
print(head(result_cards))
             name yellow_cards red_cards
1        Casemiro          166         2
2       Sam Morsy          161         6
3 Jefferson Lerma          129         3
4    Ashley Young          129         3
5   Harry Maguire          117         4
6 Bruno Fernandes          114         1
                                                                              image
1  https://img.a.transfermarkt.technology/portrait/header/16306-1699018876.jpg?lm=1
2 https://img.a.transfermarkt.technology/portrait/header/123551-1658821486.jpg?lm=1
3 https://img.a.transfermarkt.technology/portrait/header/262980-1693334146.jpg?lm=1
4  https://img.a.transfermarkt.technology/portrait/header/14086-1700736434.jpg?lm=1
5 https://img.a.transfermarkt.technology/portrait/header/177907-1663841733.jpg?lm=1
6 https://img.a.transfermarkt.technology/portrait/header/240306-1683882766.jpg?lm=1
# riwayat cedera dan absen terbanyak
query_injuries <- '[
  { "$unwind": "$injuries" },
  { "$group": {
      "_id": "$profile.name",
      "injury_count": { "$sum": 1 },
      "games_missed": { "$sum": { "$ifNull": ["$injuries.gamesMissed", 0] } },
      "image": { "$first": "$profile.imageUrl" }
    }
  },
  { "$sort": { "games_missed": -1, "injury_count": -1 } }
]'
result_injuries <- conn$aggregate(query_injuries)
colnames(result_injuries) <- c("name", "injury_count", "games_missed", "image")
print(head(result_injuries))
           name injury_count games_missed
1     Joe Gomez           13          273
2 Wesley Fofana           11          214
3 Kortney Hause            9          206
4 Danny Welbeck           15          196
5  Tyrone Mings            8          185
6    Rico Henry            7          177
                                                                              image
1 https://img.a.transfermarkt.technology/portrait/header/256178-1595946530.jpg?lm=1
2 https://img.a.transfermarkt.technology/portrait/header/475411-1683899212.jpg?lm=1
3 https://img.a.transfermarkt.technology/portrait/header/233124-1700671308.jpg?lm=1
4  https://img.a.transfermarkt.technology/portrait/header/67063-1700673547.jpg?lm=1
5 https://img.a.transfermarkt.technology/portrait/header/253677-1593437372.jpg?lm=1
6 https://img.a.transfermarkt.technology/portrait/header/339556-1684771012.jpg?lm=1

Visualisasi agregasi

#sebaran asal negara pemain 
world <- ne_countries(scale = "medium", returnclass = "sf")
world_map <- left_join(world, result_country, by = c("name" = "country"))
ggplot(data = world_map) +
  geom_sf(aes(fill = total_players), color = "white", size = 0.1) +
  scale_fill_viridis_c(option = "plasma", na.value = "gray90") +
  coord_sf(ylim = c(-65, 90), expand = FALSE) +
  labs(
    title = "Sebaran Asal Negara Pemain EPL",
    fill = "Jumlah Pemain"
  ) +
  theme_void() +
  theme(
    legend.position = "none",
    legend.key.height = unit(0.5, "cm"),
    plot.title = element_text(hjust = 0.5, face = "bold", size = 16, margin = margin(b = 5)),
    plot.margin = margin(0, 0, 0, 0, unit = "cm")
  )

# Top 10 asal negara pemain
top10_country <- result_country %>% slice_max(total_players, n = 10)
ggplot(top10_country, aes(x = reorder(country, total_players), y = total_players, fill = country)) +
  geom_col() +
  geom_text(aes(label = total_players), hjust = -0.1, fontface = "bold", size = 3.8) +
  coord_flip(clip = "off") +
  labs(
    title = "Top 10 Negara Asal Pemain EPL",
    x = "Negara",
    y = "Jumlah Pemain"
  ) +
  theme_minimal() +
  theme(
    legend.position = "none",
    plot.title = element_text(hjust = 0.5, face = "bold", size = 16),
    plot.margin = margin(5, 20, 5, 5)
  )

ggplot(result_age_pos, aes(x = factor(age), y = position, fill = total_players)) +
  geom_tile(color = "white") +
  scale_fill_viridis_c(option = "plasma") +
  labs(
    title = "Distribusi Pemain Berdasarkan Usia dan Posisi",
    x = "Usia",
    y = "Posisi",
    fill = "Jumlah"
  ) +
  theme_minimal() +
  theme(
    plot.title = element_text(hjust = 0.5, face = "bold"),
    axis.text.x = element_text(angle = 45, hjust = 1)
  )

# Rata-rata usia pemain setiap posisi
result_age_pos %>%
  group_by(position) %>%
  summarise(avg_age = weighted.mean(age, total_players)) %>%
  ggplot(aes(x = reorder(position, avg_age), y = avg_age, fill = position)) +
  geom_col() +
  geom_text(aes(label = round(avg_age, 1)), hjust = 1.5, fontface = "bold") +
  coord_flip() +
  labs(
    title = "Rata-Rata Usia Pemain per Posisi",
    x = "Posisi",
    y = "Rata-Rata Usia"
  ) +
  theme_minimal() +
  theme(legend.position = "none")

#Top 5 market value tertinggi
result_max_value$label <- paste0(
  "   ", result_max_value$name, "\n(",
  result_max_value$club, ", ", result_max_value$position, ")"
)

ggplot(result_max_value, aes(x = reorder(label, market_value), y = market_value, fill = name)) +
  geom_col() +
  geom_image(aes(image = image), size = 0.13, by = "width", nudge_y = 10000000) + 
  geom_text(
    aes(label = comma(market_value, big.mark = ".", decimal.mark = ",")),
    hjust = 1.2,
    fontface = "bold",
    size = 3.8
  ) +
  coord_flip(clip = "off") +
  scale_fill_brewer(palette = "Set3") +
  scale_y_continuous(labels = comma_format(big.mark = ".", decimal.mark = ",")) +
  labs(
    title = "Top 5 Pemain dengan Market Value Tertinggi",
    x = NULL,
    y = "Market Value (€)"
  ) +
  theme_minimal() +
  theme(
    legend.position = "none",
    axis.text.y = element_text(lineheight = 1.2, size = 10),
    plot.title = element_text(hjust = 0.5, face = "bold", size = 16),
    plot.margin = margin(5, 20, 5, 5)
  )

#Top 5 Market value terendah
result_min_value$label <- paste0(
  "   ", result_min_value$name, "\n(",
  result_min_value$club, ", ", result_min_value$position, ")"
)

ggplot(result_min_value, aes(x = reorder(label, market_value), y = market_value, fill = name)) +
  geom_col() +
  geom_image(aes(image = image), size = 0.09, by = "width", nudge_y = 5e5) +
  geom_text(
    aes(label = comma(market_value, big.mark = ".", decimal.mark = ",")),
    hjust = 1,
    fontface = "bold",
    size = 3.8
  ) +
  coord_flip(clip = "off") +
  scale_fill_brewer(palette = "Set3") +  # atau Set2, Paired, Pastel1
  labs(
    title = "Top 5 Pemain dengan Market Value Terendah",
    x = NULL,
    y = "Market Value (€)"
  ) +
  scale_y_continuous(labels = comma_format(big.mark = ".", decimal.mark = ",")) +
  theme_minimal() +
  theme(
    legend.position = "none",
    axis.text.y = element_text(lineheight = 1.2, size = 10),
    plot.title = element_text(hjust = 0.5, face = "bold", size = 16),
    plot.margin = margin(5, 20, 5, 5)
  )

#Top 10 total market value tertinggi
ggplot(result_market, aes(x = reorder(club, total_market_value), y = total_market_value)) +
  geom_col(fill = "steelblue") +
  geom_text(
    aes(label = comma(total_market_value, big.mark = ".", decimal.mark = ",")),
    hjust = 1.2,
    fontface = "bold",
    size = 3.8
  ) +
  coord_flip(clip = "off") +
  labs(
    title = "Top 10 Klub dengan Market Value Tertinggi",
    x = "",
    y = "Total Market Value (€)"
  ) +
  scale_y_continuous(labels = comma_format(big.mark = ".", decimal.mark = ",")) +
  theme_minimal() +
  theme(
    plot.title = element_text(hjust = 0.5, size = 16, face = "bold"),
    plot.margin = margin(5, 20, 5, 5)
  )

#history 5 pemain market value tertinggi dalam 5 tahun terakhir
ggplot(result_history, aes(x = date, y = market_value, color = name)) +
  geom_line(size = 1) +
  geom_point(size = 0.2) +
  scale_y_continuous(labels = comma_format(big.mark = ".", decimal.mark = ",")) +
  labs(
    title =  "Market Value History Top 5 Pemain Termahal",
    x = "Tahun",
    y = "Market Value (€)",
    color = "Pemain"
  ) +
  theme_minimal() +
  theme(
    plot.title = element_text(hjust = 0.5, face = "bold", size = 16),
    legend.position = "top"
  )
Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
ℹ Please use `linewidth` instead.

#Rata- rata market value setiap posisi
ggplot(result_pos, aes(x = reorder(position, avg_value), y = avg_value)) +
  geom_col(fill = "purple") +
  geom_text(aes(label = comma(avg_value, big.mark = ".", decimal.mark = ",")),
            hjust = 1, fontface = "bold", size = 3.8) +
  coord_flip(clip = "off") +
  labs(title = "Rata-Rata Market Value per Posisi",
       x = "Posisi", y = "Rata-Rata (€)") +
  scale_y_continuous(labels = comma_format(big.mark = ".", decimal.mark = ",")) +
  theme_minimal()

#Top 5 pemain dengan achievement terbanyak
result_achieve$label <- paste0("   ", result_achieve$name)
ggplot(result_achieve, aes(x = reorder(label, jumlah), y = jumlah, fill = name)) +
  geom_col() +
  geom_image(aes(image = image), size = 0.13, by = "width", nudge_y = 0.5) +
  geom_text(aes(label = jumlah), hjust = 1.6, fontface = "bold", size = 4) +
  coord_flip(clip = "off") +
  scale_fill_brewer(palette = "Set3") +
  scale_y_continuous(labels = comma_format(big.mark = ".", decimal.mark = ",")) +
  labs(
    title = "Top 5 Pemain dengan Jumlah Achievement Terbanyak",
    x = NULL,
    y = "Jumlah Achievement"
  ) +
  theme_minimal() +
  theme(
    legend.position = "none",
    axis.text.y = element_text(size = 10, lineheight = 1.2),
    plot.title = element_text(hjust = 0.5, face = "bold", size = 14),
    plot.margin = margin(5, 20, 5, 5)
  )

#Total transfer fee masuk setiap klub
ggplot(result_transfers, aes(x = reorder(club_to, total_fee), y = total_fee)) +
  geom_col(fill = "tomato") +
  geom_text(aes(label = comma(total_fee, big.mark = ".", decimal.mark = ",")),
            hjust = 1.2, fontface = "bold", size = 3.8) +
  coord_flip(clip = "off") +
  labs(title = "Top 10 Klub dengan Total Fee Transfer Tertinggi",
       x = "Klub", y = "Total Biaya Transfer (€)") +
  scale_y_continuous(labels = comma_format(big.mark = ".", decimal.mark = ",")) +
  theme_minimal()

#pemain dengan menit bermain terbanyak
result_minutes$label <- paste0("   ", result_minutes$name)

ggplot(result_minutes, aes(x = reorder(label, total_minutes), y = total_minutes, fill = name)) +
  geom_col() +
  geom_image(aes(image = image), size = 0.13, by = "width", nudge_y = 50) +
  geom_text(aes(label = comma(total_minutes, big.mark = ".", decimal.mark = ",")),
            hjust = 2, fontface = "bold", size = 4) +
  coord_flip(clip = "off") +
  scale_fill_brewer(palette = "Set2") +
  scale_y_continuous(labels = comma_format(big.mark = ".", decimal.mark = ",")) +
  labs(
    title = "Top 5 Menit Bermain Terbanyak (EPL 2024/25)",
    x = NULL,
    y = "Menit Bermain"
  ) +
  theme_minimal() +
  theme(
    legend.position = "none",
    axis.text.y = element_text(size = 10, lineheight = 1.2),
    plot.title = element_text(hjust = 0.5, face = "bold", size = 16),
    plot.margin = margin(5, 20, 5, 5)
  )

#pemain dengan goal terbanyak dalam 5 musim terakhir
result_goals$label <- paste0("   ", result_goals$name)

ggplot(result_goals, aes(x = reorder(label, goals), y = goals, fill = name)) +
  geom_col() +
  geom_image(aes(image = image), size = 0.13, by = "width", nudge_y = 5) +
  geom_text(aes(label = goals), hjust = 1.5, fontface = "bold", size = 4) +
  coord_flip(clip = "off") +
  labs(
    title = "Top 5 Pencetak Gol EPL (5 Musim Terakhir)",
    x = NULL,
    y = "Jumlah Gol"
  ) +
  scale_y_continuous(labels = comma_format(big.mark = ".", decimal.mark = ",")) +
  scale_fill_brewer(palette = "Set2") +  # atau Set3, Pastel1, Dark2, dll
  theme_minimal() +
  theme(
    legend.position = "none",
    axis.text.y = element_text(size = 10, lineheight = 1.2),
    plot.title = element_text(hjust = 0.5, face = "bold", size = 16),
    plot.margin = margin(5, 20, 5, 5)
  )

# pemain paling sering pindah klub dan total transfer fee
result_transfer_count <- result_transfer_count %>% 
  filter(!is.na(image)) %>% 
  mutate(label = paste0("   ", name))

top_transfer <- result_transfer_count %>% slice_max(transfer_count, n = 5)

ggplot(top_transfer, aes(x = reorder(label, transfer_count), y = transfer_count, fill = name)) +
  geom_col() +
  geom_image(aes(image = image), size = 0.12, by = "width", nudge_y = 0.5) +
  geom_text(aes(label = paste0("Fee: ", comma(total_fee, big.mark = ".", decimal.mark = ","))),
             hjust = 1.5, fontface = "bold", size = 3.5) +
  coord_flip(clip = "off") +
  scale_fill_brewer(palette = "Paired") +
  labs(
    title = "Top 5 Pemain Paling Sering Pindah Klub",
    x = NULL,
    y = "Jumlah Transfer"
  ) +
  theme_minimal() +
  theme(
    legend.position = "none",
    axis.text.y = element_text(size = 10, lineheight = 1.2),
    plot.title = element_text(hjust = 0.5, face = "bold", size = 16),
    plot.margin = margin(5, 20, 5, 5)
  )

# top 5 Yellow Cards
plot_yellow <- result_cards %>%
  mutate(label = paste0("   ", name)) %>%
  slice_max(yellow_cards, n = 5) %>%
  ggplot(aes(x = fct_reorder(label, yellow_cards), y = yellow_cards, fill = name)) +
  geom_col() +
  geom_image(aes(image = image), size = 0.13, by = "width", nudge_y = 0.5) +
  geom_text(aes(label = yellow_cards), hjust = 2.3, fontface = "bold", size = 3.5) +
  coord_flip(clip = "off") +
  scale_fill_brewer(palette = "YlOrBr") +
  labs(
    title = "Top 5 Pemain dengan Kartu Kuning Terbanyak",
    x = NULL,
    y = "Jumlah Kartu Kuning"
  ) +
  theme_minimal() +
  theme(
    legend.position = "none",
    axis.text.y = element_text(size = 10, lineheight = 1.2),
    plot.title = element_text(hjust = 0.5, face = "bold", size = 16),
    plot.margin = margin(5, 20, 5, 5)
  )
print(plot_yellow)

#top 5 red card
plot_red <- result_cards %>%
  mutate(label = paste0("   ", name)) %>%
  slice_max(red_cards, n = 5) %>%
  ggplot(aes(x = fct_reorder(label, red_cards), y = red_cards, fill = name)) +
  geom_col() +
  geom_image(aes(image = image), size = 0.14, by = "width", nudge_y = 0.2) +
  geom_text(aes(label = red_cards), hjust = 2.8, fontface = "bold", size = 3.5) +
  coord_flip(clip = "off") +
  scale_fill_brewer(palette = "YlOrBr") +
  labs(
    title = "Top 5 Pemain dengan Kartu Merah Terbanyak",
    x = NULL,
    y = "Jumlah Kartu Merah"
  ) +
  theme_minimal() +
  theme(
    legend.position = "none",
    axis.text.y = element_text(size = 10, lineheight = 1.2),
    plot.title = element_text(hjust = 0.5, face = "bold", size = 16),
    plot.margin = margin(5, 20, 5, 5)
  )
print(plot_red)

#pemain dengan absen pertandingan terbanyak karena cedera
plot_games_missed <- result_injuries %>%
  mutate(label = paste0("   ", name)) %>%
  slice_max(games_missed, n = 5) %>%
  ggplot(aes(x = fct_reorder(label, games_missed), y = games_missed, fill = name)) +
  geom_col() +
  geom_image(aes(image = image), size = 0.13, by = "width", nudge_y = 0.9) +
  geom_text(aes(label = games_missed), hjust = 2.4, fontface = "bold", size = 3.5) +
  coord_flip(clip = "off") +
  scale_fill_brewer(palette = "Set2") +
  labs(
    title = "Top 5 Pemain dengan Absen Pertandingan Terbanyak karena Cedera",
    x = NULL,
    y = "Games Missed"
  ) +
  theme_minimal() +
  theme(
    legend.position = "none",
    axis.text.y = element_text(size = 10, lineheight = 1.2),
    plot.title = element_text(hjust = 0.5, face = "bold", size = 16),
    plot.margin = margin(5, 20, 5, 5)
  )
print(plot_games_missed)