Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Title Defenses
library(engsoccerdata)
library(tidyverse)
## get data of all top-tier seasons
df <- rbind(england, england_current()) %>% filter(tier==1)
## Get champions from each season.
df.seasons <- split(df, df$Season)
df.tables <- lapply(df.seasons, function(x) maketable_eng(x, tier=1, Season=x[1,2]))
champs <- unlist(lapply(df.tables, function(x) x[1,1]))
champs.df <- data.frame(champs=champs, Season=as.numeric(names(champs)))
## Get record of each team in following Season.
results=NULL
for(i in 1:(length(champs)-1)){
results[[i]] <- df %>%
filter(Season==champs.df$Season[i]+1) %>%
homeaway() %>%
filter(team==champs.df$champs[i]) %>%
mutate(gameno=row_number(),
pts=ifelse(gf>ga, 3, ifelse(gf<ga, 0, 1)),
cumpts=cumsum(pts))
}
## Make into one dataframe and plot:
resdf <- do.call('rbind', results)
resdf$id <- paste(resdf$Season, resdf$team, sep="-")
#highlight Chelsea 2015 also by making separate grp
resdf$grp <- ifelse(resdf$Season>=2015, 1, 0)
#make Leicester City 2016 own line & Manchester City 1937 own line:
leics2016 <- resdf %>% filter(Season==2016)
manc1937 <- resdf %>% filter(Season==1937)
resdf1 <- resdf %>% filter(Season!=2016) %>% filter(Season!=1937) %>% ungroup()
p = ggplot(resdf1, aes(gameno, cumpts, group=id, color=grp)) +
geom_line(data=manc1937, aes(gameno, cumpts, group=id, color='pink'), lwd=1.1) +
geom_line(aes(group=id, color=factor(grp),alpha=.5)) +
geom_line(data=leics2016, aes(gameno, cumpts, group=id, color=factor(grp)), lwd=1.1) +
xlab("Game number") + ylab("Cumulative points") +
scale_color_manual(values=c("gray80", "blue", "pink")) +
ggtitle("How Champions Do The Following Season") +
theme(
plot.title = element_text(hjust=0,vjust=1, size=rel(1.7)),
panel.background = element_blank(),
panel.grid.major.y = element_line(color="gray95"),
panel.grid.major.x = element_line(color="gray95"),
panel.grid.minor = element_blank(),
plot.background = element_blank(),
text = element_text(color="gray20", size=10),
axis.text = element_text(size=rel(1.0)),
axis.text.x = element_text(color="gray20",size=rel(1.5)),
axis.text.y = element_text(color="gray20", size=rel(1.5)),
axis.title.x = element_text(size=rel(1.5), vjust=0),
axis.title.y = element_text(size=rel(1.5), vjust=1),
axis.ticks.y = element_blank(),
axis.ticks.x = element_blank(),
legend.position = "none"
)
# create an svg image
library(svglite)
svglite("plot.svg", width = 8, height = 7)
p
dev.off()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment