Skip to content

Instantly share code, notes, and snippets.

@RamiKrispin
Created December 31, 2021 18:09
Show Gist options
  • Save RamiKrispin/6c25075c1c08c7683a9011aab4d19228 to your computer and use it in GitHub Desktop.
Save RamiKrispin/6c25075c1c08c7683a9011aab4d19228 to your computer and use it in GitHub Desktop.
Plotting Daily New COVID19 Cases in the US
# Plotting COVID19 daily new cases in the US
# Using the following libraries:
# coronavirus for data
# plotly for dataviz
# dplyr for data manipulation
library(coronavirus)
library(plotly)
library(dplyr)
df <- refresh_coronavirus_jhu()
head(df)
max(df$date)
# Filter the data for US confirmed cases
df_us <- df %>% filter(location == "US",
data_type == "cases_new") %>%
select(date, cases = value) %>%
arrange(date)
# Creating lags for moving average
d <- lapply(0:6, function(i){
d <- df_us %>% select(date, cases) %>%
mutate(cases_lag = lag(cases, n = i),
lag = i)
return(d)
}) %>%
dplyr::bind_rows() %>%
dplyr::group_by(date) %>%
dplyr::summarise(cases = mean(cases),
cases_ma = mean(cases_lag, na.rm = TRUE))
head(d)
# Plot setting
mv_color <- "red"
bg_color <- "#fdfffc"
# Plotting the cases
plot_ly(data = d,
x = ~ date,
y = ~ cases,
type = "scatter",
mode = "markers",
name = "Daily New Cases") %>%
add_lines(x = ~ date, y = ~ cases_ma,
line = list(color = mv_color, width = 3),
name = "7 Days Moving Average") %>%
layout(title = "US Daily New COVID-19 Cases",
yaxis = list(title = "Cases",
showgrid = TRUE),
xaxis = list(title = "Source: Johns Hopkins University Center for Systems Science and Engineering",
showgrid = FALSE),
legend = list(x = 0.1, y = 0.9),
paper_bgcolor= bg_color,
plot_bgcolor= bg_color,
margin = list(b = 65, t = 45, r = 40, l = 40))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment