# Load the required libraries
# See recipes documenation for details.

library(nCov2019)
library(forcats)
library(ggplot2)
library(maps)

library(chinamap)
library(ggrepel)

# Obtain the data for the Wuhan virus.
data <- get_nCov2019(lang='en')

# Global infections.
pdf(file = "infections-Globally.pdf", width = 10)
plot(data)
dev.off()

# China map.
cn = get_map_china()

## Translate province.
cn$province <- trans_province(cn$province)

# Infections broken down by chinese provinces.
pdf(file = "infections-China.pdf", width = 10)
plot(data, region='china', chinamap=cn, font.size=2)
dev.off()

# Summary data 
results = summary(data, by="today")
write.csv(results, "infection-summary.txt")

# Visualize the cumulative summary data,
ggplot(summary(data), aes(as.Date(date, "%m.%d"), as.numeric(confirm))) +
  geom_col(fill='firebrick') + theme_minimal(base_size = 14) +
  xlab(NULL) + ylab(NULL) + 
  labs(caption = paste("accessed date:", time(data)))

# Saving the plot.
fname = "infections-summary.pdf"
ggsave(fname)

plot_province <- function (data, name) {
 
  # select province
  d = data[name] 
  d$confirm = as.numeric(d$confirm)
  ggplot(d, aes(name, confirm)) +
    geom_col(fill = 'steelblue') + coord_flip() +
    geom_text(aes(y = confirm + 2, label = confirm), hjust = 0) +
    theme_minimal(base_size = 14) +
    scale_y_continuous(expand = c(0, 10)) +
    xlab(NULL) + ylab(NULL)
  
  # Save the plot.
  fname = paste("infections-", name, ".pdf", sep = "")
  ggsave(fname)
  
}

# Provinces to plot.
labels = c("Anhui", "Hubei", "Hunan")

for (name in labels){
  plot_province(data, name)
}