Created
May 9, 2020 23:29
-
-
Save RamiKrispin/4487739b41d9d4d8848cf93366404cf2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#--------------------------------------------------------- | |
# Creating a trajectory plot for covid19 confirmed cases | |
# Required packages - dplyr, tidyr, and plotly packages | |
# Data - coronavirus package | |
#--------------------------------------------------------- | |
# To get the most update data use the Github version | |
#devtools::install_github("RamiKrispin/coronavirus") | |
library(coronavirus) | |
`%>%` <- magrittr::`%>%` | |
# Trajectory function | |
covid_trajec <- function(min_case = 100, max_days = 80, country){ | |
country_df <- lapply(country, function(i){ | |
df <- coronavirus %>% dplyr::filter(type == "confirmed", Country.Region == i) %>% | |
dplyr::group_by(date) %>% | |
dplyr::summarise(cases = sum(cases)) %>% | |
dplyr::ungroup() %>% | |
dplyr::arrange(date) %>% | |
dplyr::mutate(total = cumsum(cases), | |
country = i) %>% | |
dplyr::filter(total > min_case) %>% | |
dplyr::select(-cases, -date) | |
if(nrow(df) > max_days){ | |
df <- df[1:max_days,] | |
} | |
df$index <- 1:nrow(df) | |
return(df) | |
}) %>% dplyr::bind_rows() %>% | |
tidyr::pivot_wider(names_from = country, values_from = total) %>% | |
as.data.frame() | |
p <- plotly::plot_ly() | |
for(i in 2:ncol(country_df)){ | |
p <- p %>% | |
plotly::add_lines(x = country_df$index, | |
y = country_df[, i], | |
name = names(country_df)[i], line = list(width = 2)) | |
} | |
# Set or modify here the layout/titles | |
p <- p %>% plotly::layout(title = "Covid19 Confirmed Cases Trajectory Plot", | |
yaxis = list(title = "Cumulative Positive Cases",type = "log"), | |
xaxis = list(title = paste("Days since the total positive cases surpass", min_case)), | |
hovermode = "compare") | |
return(p) | |
} | |
# Example for function setting | |
min_case <- 100 | |
max_days <- 80 | |
country <- c("China", "Italy", "Iran", "United Kingdom", "Spain", "France", "Russia", "Korea, South", "US") | |
covid_trajec(min_case = min_case, max_days = max_days, country = country) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is very nice.