Skip to content

Instantly share code, notes, and snippets.

@theosanderson
Created January 13, 2022 19:28
Show Gist options
  • Select an option

  • Save theosanderson/0060a56836cce96a64b0cb2ccb1cbd31 to your computer and use it in GitHub Desktop.

Select an option

Save theosanderson/0060a56836cce96a64b0cb2ccb1cbd31 to your computer and use it in GitHub Desktop.
library(readxl)
library(curl)
library(tidyverse)
file = "https://www.ons.gov.uk/file?uri=%2fpeoplepopulationandcommunity%2fhealthandsocialcare%2fconditionsanddiseases%2fdatasets%2fcoronaviruscovid19antibodydatafortheuk%2f2022/20220113covid19infectionsurveydatasets1.xlsx"
temp <- tempfile()
temp <- curl_download(url=file, destfile=temp, quiet=FALSE, mode="wb")
get_data = function(sheet, threshold ){
data<- read_excel(temp,sheet=sheet,range="A6:AT61")
data[data=="*"] <- NA
data = data %>% mutate(across(-`Weekly period`,as.numeric))
headings = read_excel(temp,sheet=sheet,range="A5:AT5",col_names = F)
ages = unique(c(t(headings)))
ages = ages[!is.na(ages)]
colnames(data)[2:46] = paste(rep(ages,each=5),colnames(data)[2:46] ,sep="_")
output = data %>% pivot_longer(-`Weekly period`) %>% separate(name,into=c("Age_range","Type"),sep="_") %>% separate(Type,into=c("Type"),sep="\\.\\.\\.") %>% pivot_wider(names_from=Type,values_from=value) %>% separate(`Weekly period`,into=c("from","to"),sep=" to ") %>% mutate(from=lubridate::dmy(from),to=lubridate::dmy(to), mid = from + (to-from)/2 ) %>% mutate(positivity = `Modelled % testing positive for COVID-19 antibodies`/100, lower = `95% Lower credible interval`/100,, upper = `95% Upper credible interval`/100) %>% mutate(Age_range=gsub("Age ","",Age_range))
output$threshold= threshold
return (output)
}
lower = get_data("1c","Lower")
higher = get_data("1g","Higher")
both = bind_rows(lower,higher)
both$threshold=factor(as.character(both$threshold),levels=c("Lower","Higher"))
library(gganimate)
anim_stat=ggplot(both ,aes(y=positivity,fill=threshold,x=Age_range,ymin=lower,ymax=upper,group=threshold))+geom_area(position="identity",alpha=1,color="black",lwd=0.4)+theme_minimal()+scale_fill_manual(values=c("#b5bef7","#7D8DE9"))+scale_color_manual(values=c("#b5bef7","#7D8DE9"))+scale_y_continuous(label=scales::percent)+labs(title = '{frame_time}',y="Percent testing positive for antibodies",x="Age range",fill="Level",caption="Data: anti-S antibody data from ONS CIS for England")+geom_errorbar(width=0.2,alpha=0.2,color="black")+ theme(plot.title = element_text(size=15))
anim_stat
anim = anim_stat+transition_time(mid)
a <- animate(anim, renderer = file_renderer("~/output_movie/"),height=500*1.5,width=800*1.5,res=180,nframes = 500)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment