Data

Row

Database

Column

confirmed cases in world

434273109

deaths in world

5499128

death rate in world

1.3

recovered in world

0

recovery rate

0

World Map

Row

Confirmed

Deaths Rate

Row

Confirmed vs Death

Total Death by Country

Cases

Top 20

Barchart

Barchart

Per million people

Per million people

Cases around the World - log

Cases around the World - log

Cases

Row

Database

Graphic

Column

confirmed cases

29887191

deaths

659508

death rate

2.2

recovered

17771228

recovery rate

59.5

Map by States

Map by States

Map by City

Map by City

Table by State

Table by State

Table by City

Table by City

SIR Model

Row

SIR

Modelo SIR 2019-nCoV Brasil

Methodology

A new invisible enemy, only 30kb in size, has emerged and is on a killing spree around the world: 2019-nCoV, the Novel Coronavirus!

It has already killed more people than the SARS pandemic and its outbreak has been declared a Public Health Emergency of International Concern (PHEIC) by the World Health Organization (WHO).

There are many epidemiological models around, we will use one of the simplest here, the so-called SIR model. We will use this model with the latest data from the current outbreak of 2019-nCoV.

There are three groups of people: those that are healthy but susceptible to the disease (S), the infected (I) and the people who have recovered (R):

To model the dynamics of the outbreak we need three differential equations, one for the change in each group, where \(\beta\) is the parameter that controls the transition between S and I and \(\gamma\) which controls the transition between I and R:

\[{\frac{dS}{dt} = - \frac{\beta I S}{N}}\]

\[{\frac{dI}{dt} = \frac{\beta I S}{N}- \gamma I}\]

\[{\frac{dR}{dt} = \gamma I}\]

To fit the model to the data we need two things: a solver for differential equations and an optimizer. To solve differential equations the function ode from the deSolve package (on CRAN) is an excellent choice, to optimize we will use the optim function from base R. Concretely, we will minimize the sum of the squared differences between the number of infected I at time t and the corresponding number of predicted cases by our model \(^{I}\)(t):

One important number is the so-called basic reproduction number (also basic reproduction ratio) \(R_0\) (pronounced “R naught”) which basically shows how many healthy people get infected by a sick person on average:

\[R_0 = {\frac{\beta}{\gamma}}\]

So, \(R_0\) is 2.2, below the value that many researchers and the WHO give and which is around the same range of SARS, Influenza or Ebola (while transmission of Ebola is via bodily fluids and not airborne droplets). Additionally, according to this model, the height of a possible pandemic would be reached in 22 December (300 days after it started) with over 74 millions brazilians infected and over 165 thousand dead!

Do not panic! All of this is preliminary and hopefully (probably!) false. When you play along with the above model you will see that the fitted parameters are far from stable. On the one hand, the purpose of this dashboard was just to give an illustration of how such analyses are done in general with a very simple (probably too simple!) model, on the other hand, we are in good company here; the renowned scientific journal Nature writes:

Researchers are struggling to accurately model the outbreak and predict how it might unfold.

On the other hand, I wouldn’t go that far that the numbers are impossibly high. H1N1, also known as swine flu, infected up to 1.5 billion people during 2009/2010 and nearly 600,000 died. And this wasn’t the first pandemic of this proportion in history (think Spanish flu). Yet, this is one of the few times where I hope that my model is wrong and we will all stay healthy!

source: R-bloggers

Column

R0

2.2

infected

7485

peak epidemic date

22 December 2020

death rate

2.2 %

deaths with current death rate

165

Compare

Cases after first confirmed case


After 763 days of the first confirmed case in each country

Brazil: 29887191 cases, first case 26 February 2020

Italy: 12910506 cases, first case 31 January 2020

Spain: 11100428 cases, first case 01 February 2020

US: 78660508 cases, , first case 22 January 2020

Deaths after first confirmed case


After 763 days of the first confirmed case in each country

Brazil: 659508 deaths, first case 26 February 2020

Italy: 155399 deaths, first case 31 January 2020

Spain: 100413 deaths, first case 01 February 2020

US: 940387 deaths, , first case 22 January 2020

Recovered after first confirmed case


After 763 days of the first confirmed case in each country

Brazil: 17771228 recovered, first case 26 February 2020

Italy: 0 recovered, first case 31 January 2020

Spain: 0 recovered, first case 01 February 2020

US: 0 recovered, first case 22 January 2020

Cases after 100 confirmed case


Comparison between Italy, Germany, Spain, and Brazil after the 100th case and the sum of these countries without Brazil

Why sum of total cases of these countries?

The population of Brazil is similar of the others countries together

About

Column

Curriculum

---
title: "covid-19"
autor: "Cid Póvoas"
output: 
  flexdashboard::flex_dashboard:
    logo: "corona.png"
    favicon: "corona.ico"
    #self_contained: false
    orientation: columns
    storyboard: true
    vertical_layout: fill
    theme: flatly
    source_code: embed
editor_options: 
  chunk_output_type: inline
---

```{r setup, include=FALSE}
Sys.setlocale(category = "LC_ALL", locale = "English_United States.1252")


library(magrittr) 
library(lubridate)
library(tidyverse)
library(gridExtra)
library(ggforce) 
library(kableExtra) 
library(leaflet) 
library(plotly)

pkg <- c("rvest",
         "readxl",
         "dplyr",
         "knitr",
         "kableExtra",
         "stringr",
         "spData",
         "sf",
         "DT")


sapply(pkg,
       library,
       character.only = TRUE,
       logical.return = T)

options(DT.options = list(scrollY="100vh"))

raw.data.confirmed <- read.csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv')
raw.data.deaths <- read.csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv')
raw.data.recovered <- read.csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_recovered_global.csv')
dim(raw.data.confirmed)

n.col <- ncol(raw.data.confirmed)
## get dates from column names
dates <- names(raw.data.confirmed)[5:n.col] %>% substr(2,9) %>% mdy()
range(dates)
min.date <- min(dates)
max.date <- max(dates)
min.date.txt <- min.date %>% format('%d %b %Y')
max.date.txt <- max.date %>% format('%d %b %Y')

cleanData <- function(data) {
  data %<>% select(-c(Province.State, Lat, Long)) %>% rename(country=Country.Region)
  data %<>% gather(key=date, value=count, -country)
  data %<>% mutate(date = date %>% substr(2,9) %>% mdy())
  data %<>% group_by(country, date) %>% summarise(count=sum(count, na.rm=T)) %>% as.data.frame()
  return(data)
}

data.confirmed <- raw.data.confirmed %>% cleanData() %>% rename(confirmed=count)
data.deaths <- raw.data.deaths %>% cleanData() %>% rename(deaths=count)
data.recovered <- raw.data.recovered %>% cleanData() %>% rename(recovered=count)
## merge above 3 datasets into one, by country and date
data <- data.confirmed %>% merge(data.deaths, all=T) %>% merge(data.recovered, all=T)

library(wpp2019)
data(pop)
popz <- pop[c(2,17)]


names(popz) <- c("country", "pop")
popz$country <- as.factor(popz$country)
levels(popz$country)[233] <- "US"

subset(popz, country == "US")
data <- merge(popz,data)

#data$pop <- gsub("[[:blank:].]", "", data$pop)
#data$pop <- as.integer(data$pop)

db <- data

```

# Info {.sidebar}
=====================================

The data source used for this analysis is the 2019 Novel Coronavirus COVID-19 (2019-nCoV) Data Repository built by the Center for Systems Science and Engineering, John Hopkins University

This is an analysis report of the Novel Coronavirus (COVID-19) around the world, to demonstrate data processing and visualisation with R, tidyverse and ggplot2. This report will be updated from time to time, with new data and more analysis

Dashboard by [Cid Edson Póvoas](mailto:cidedson@gmail.com)

[Facebook](http://www.facebook.com/cidedson) | [Instagram](http://www.instagram.com/cidedson) | [Twitter](http://www.twitter.com/cidedson)

adapted: [Yanchang Zhao, COVID-19 Data Analysis with R – Worldwide. RDataMining.com, 2020.](http://www.rdatamining.com/docs/Coronavirus-data-analysis-world.pdf)

update: `r max.date.txt` 


Data {data-orientation=rows}
=====================================  

Row {.tabset .tabset-fade}
-------------------------------------

### Database  

```{r data}

data.ultimo <- data %>% filter(date == max(date), country!="World") %>%
  select(country,
         confirmed,
         recovered, deaths, pop) %>%
  mutate(confirmed.pop = ((confirmed/pop*1000) %>% round(0)),
         deaths.pop = ((deaths/pop*1000) %>% round(0)))




DT::datatable(
    data.ultimo,
    rownames = FALSE, 
    filter = "top",
    extensions = c('Buttons', 'Scroller'),
    options = list(
      dom = 'Blfrtip',
      bPaginate = TRUE,
      buttons = c('csv', 'excel'),
      deferRender = T,
  scroller = TRUE)) %>%
  formatStyle(
    'deaths.pop',
    background = styleColorBar(data.ultimo$deaths.pop, 'red'),
    backgroundSize = '100% 90%',
    backgroundRepeat = 'no-repeat',
    backgroundPosition = 'center'
  ) %>%
  formatStyle(
    'confirmed.pop',
    background = styleColorBar(data.ultimo$confirmed.pop, 'orange'),
    backgroundSize = '100% 90%',
    backgroundRepeat = 'no-repeat',
    backgroundPosition = 'center'
  ) 

```

Column {data-width=120}
----------
### confirmed cases in world

```{r}

library(flexdashboard)
valueBox(round(sum(data.ultimo$confirmed),1), icon = "fa-meh", href="#brazil")
```

### deaths in world

```{r}

valueBox(round(sum(data.ultimo$deaths),1), icon = "fa-skull")

```

### death rate in world
```{r}

valueBox(paste(round(sum(data.ultimo$deaths)/sum(data.ultimo$confirmed)*100,1)), icon = "fa-percentage")

```


### recovered in world

```{r}
valueBox(round(sum(data.ultimo$recovered),1), icon = "fa-heartbeat")

```

### recovery rate

```{r}

valueBox(paste(round(sum(data.ultimo$recovered)/sum(data.ultimo$confirmed)*100,1)), icon = "fa-percentage")

```



World Map {data-navmenu="World"  data-icon="fa-globe"}
=====================================  
Row {.tabset .tabset-fade}
-----------------------------------------------------------------------
### Confirmed 

```{r anova}

x <- raw.data.confirmed
x$confirmed <- x[, ncol(x)]
x %<>% select(c(Country.Region, Province.State, Lat, Long, confirmed)) %>%
  mutate(txt=paste0(Country.Region, ' - ', Province.State, ': ', confirmed))


m <- leaflet(width=1200, height=800) %>% addTiles()

m %<>% addCircleMarkers(x$Long, x$Lat,
                        radius=2+log2(x$confirmed), stroke=F,
                        color='orange', fillOpacity=0.5,
                        popup=x$txt)
m

```


```{r, fig.height=10, fig.width=12}

db <- data

data <- data.confirmed %>% merge(data.deaths, all=T) %>% merge(data.recovered, all=T)


data.world <- data %>% group_by(date) %>%
  summarise(country='World',
            confirmed = sum(confirmed, na.rm=T),
            deaths = sum(deaths, na.rm=T),
            recovered = sum(recovered, na.rm=T))

data %<>% rbind(data.world)
## current confirmed cases
data %<>% mutate(current.confirmed = confirmed - deaths - recovered)

## sort by country and date
data %<>% arrange(country, date)
## daily increases of deaths and recovered cases
## set NA to the increases on day1
n <- nrow(data)
day1 <- min(data$date)
data %<>% mutate(new.confirmed = ifelse(date == day1, NA, confirmed - lag(confirmed, n=1)),
                 new.deaths = ifelse(date == day1, NA, deaths - lag(deaths, n=1)),
                 new.recovered = ifelse(date == day1, NA, recovered - lag(recovered, n=1)))
## change negative number of new cases to zero
data %<>% mutate(new.confirmed = ifelse(new.confirmed < 0, 0, new.confirmed),
                 new.deaths = ifelse(new.deaths < 0, 0, new.deaths),
                 new.recovered = ifelse(new.recovered < 0, 0, new.recovered))

## death rate based on total deaths and recovered cases
data %<>% mutate(rate.upper = (100 * deaths / (deaths + recovered)) %>% round(1))
## lower bound: death rate based on total confirmed cases
data %<>% mutate(rate.lower = (100 * deaths / confirmed) %>% round(1))
## death rate based on the number of death/recovered on every single day
data %<>% mutate(rate.daily = (100 * new.deaths / (new.deaths + new.recovered)) %>% round(1))
data %<>% mutate(recovery.rate = (100 * recovered / confirmed) %>% round(1))

## convert from wide to long format, for drawing area plots
data.long <- data %>%
  select(c(country, date, confirmed, current.confirmed, recovered, deaths)) %>%
  gather(key=type, value=count, -c(country, date))
## set factor levels to show them in a desirable order
data.long %<>% mutate(type=recode_factor(type, confirmed='Total Confirmed',
                                         current.confirmed='Current Confirmed',
                                         recovered='Recovered',
                                         deaths='Deaths'))
## convert from wide to long format, for drawing area plots
rates.long <- data %>%
  # filter(country %in% top.countries) %>%
  select(c(country, date, rate.upper, rate.lower, rate.daily)) %>%
  # mutate(country=factor(country, levels=top.countries)) %>%
  gather(key=type, value=count, -c(country, date))
# set factor levels to show them in a desirable order
rates.long %<>% mutate(type=recode_factor(type, rate.daily='Daily',
                                          rate.lower='Lower bound',
                                          rate.upper='Upper bound'))

## ranking by confirmed cases
data.latest.all <- data %>% filter(date == max(date)) %>%
  select(country, date,
         confirmed, new.confirmed, current.confirmed,
         recovered, deaths, new.deaths, death.rate=rate.lower, recovery.rate) %>%
  mutate(ranking = dense_rank(desc(confirmed)))


k <- 20
## top 20 countries: 21 incl. 'World'
top.countries <- data.latest.all %>% filter(ranking <= k + 1) %>%
  arrange(ranking) %>% pull(country) %>% as.character()
#top.countries %>% setdiff('World') %>% print()

top.countries %<>% c('Others')
## put all others in a single group of 'Others'
data.latest <- data.latest.all %>% filter(!is.na(country)) %>%
  mutate(country=ifelse(ranking <= k + 1, as.character(country), 'Others')) %>%
  mutate(country=country %>% factor(levels=c(top.countries)))

data.latest %<>% group_by(country) %>%
  summarise(confirmed=sum(confirmed,na.rm = T), new.confirmed=sum(new.confirmed,na.rm = T),
            current.confirmed=sum(current.confirmed,na.rm = T),
            recovered=sum(recovered,na.rm = T), deaths=sum(deaths,na.rm = T), 
            new.deaths=sum(new.deaths,na.rm = T)) %>%
  mutate(death.rate= (100 * deaths/confirmed)  %>% round(1),
         recovery.rate= (100 * recovered/confirmed) %>% round(1))


data.latest %<>% select(c(country, confirmed, deaths, death.rate, recovered,recovery.rate,
                          new.confirmed, new.deaths, current.confirmed))
#data.latest %>% mutate(death.rate=death.rate %>% format(nsmall=1) %>% paste0('%'))
## convert from wide to long format, for drawing area plots
data.latest.long <- data.latest %>% filter(country!='World') %>%
  gather(key=type, value=count, -country)  #%>% mutate(count=count %>% round(1))
## set factor levels to show them with proper text and in a desirable order
data.latest.long %<>% mutate(type=recode_factor(type,
                                                confirmed='Total Confirmed',
                                                deaths='Total Deaths',
                                                death.rate='Death Rate (%)',
                                                new.confirmed='New Confirmed (compared with one day before)',
                                                new.deaths='New Deaths (compared with one day before)',
                                                current.confirmed='Current Confirmed',
                                                recovery.rate='Recovery Rate (%)',
                                                recovered='Recovered'))
## bar chart
w <- data.latest.long %>% ggplot(aes(x=country, y=count, fill=country, group=country)) +
  geom_bar(stat='identity') +
  #geom_text(aes(label=count, y=count), size=21, vjust=-1) +
  xlab('') + ylab('') +
  labs(title=paste0('Top 20 Countries with Most Confirmed Cases - ', max.date.txt)) +
  scale_fill_discrete(name='Country', labels=aes(count)) +
  theme_minimal()+
  theme(legend.title=element_blank(),
        legend.position='none',
        plot.title=element_text(size=11),
        axis.text=element_text(size=7),
        axis.text.x=element_text(angle=45, hjust=1)) +
  facet_wrap(~type, ncol=2, scales='free_y')

#w
```

Deaths Rate {data-navmenu="World"  data-icon="fa-percentage"}
=====================================  
Row {.tabset .tabset-fade}
-------------------------------------

### Confirmed vs Death


```{r, fig.height=6, fig.width=14}

# linetypes <- rep(c("dotted", "dashed", "solid"), each=8)
# colors <- rep(c('grey', 'yellow', 'purple', 'orange', 'green', 'red', 'blue', 'black'), 3)
linetypes <- rep(c("solid", "dashed", "dotted"), each=8)
colors <- rep(c('black', 'blue', 'red', 'green', 'orange', 'purple', 'yellow', 'grey'), 3)
dt <- data
dfw <- dt %>% filter(country %in% setdiff(top.countries, c('World', 'Others'))) %>%
mutate(country=country %>% factor(levels=c(top.countries)))
p <- dfw %>% ggplot(aes(x=confirmed, y=deaths, group=country)) +
geom_line(aes(color=country, linetype=country)) +
xlab('Total Confirmed') + ylab('Total Deaths') +
scale_linetype_manual(values=linetypes) +
scale_color_manual(values=colors) +
theme(legend.title=element_blank(),
legend.text=element_text(size=8),
legend.key.size=unit(0.5, 'cm'))
 
p1 <-p + scale_x_log10() + scale_y_log10()

grid.arrange(p,p1, ncol=2)

```

### Total Death by Country  

```{r, fig.height=7, fig.width=16}

df <- data.latest %>% filter(country %in% setdiff(top.countries, 'World'))
plot1 <- df %>% ggplot(aes(x=confirmed, y=deaths, col=death.rate, size=current.confirmed, label=country)) +
scale_size(name='Current Confirmed', trans='log2', breaks=c(1e3, 2e3, 5e3, 1e4, 2e4, 4e4)) +
geom_text(aes(label=country), size=2.5, check_overlap=T, vjust=2) +
geom_point() +
xlab('Total Confirmed') + ylab('Total Deaths') +
labs(col="Death Rate (%)") +
scale_color_gradient(low='#56B1F7', high='#132B43') +
scale_x_log10() + scale_y_log10()
plot2 <- df %>% ggplot(aes(x=new.confirmed, y=new.deaths, col=death.rate, size=current.confirmed, label=country)) +
scale_size(name='Current Confirmed', trans='log2', breaks=c(1e3, 2e3, 5e3, 1e4, 2e4, 4e4)) +
geom_text(aes(label=country), size=2.5, check_overlap=T, vjust=2) +
geom_point() +
xlab('New Confirmed') + ylab('New Deaths') +
labs(col="Death Rate (%)") +
scale_color_gradient(low='#56B1F7', high='#132B43') +
scale_x_log10() + scale_y_log10()
grid.arrange(plot1, plot2)

```

Cases {data-navmenu="World"  data-icon="fa-check"}
=======================================

### Top 20

```{r}

data.latest %>% mutate(death.rate = death.rate %>% round(1) %>%
                         format(nsmall = 1) %>%
                         paste0('%'),
                       recovery.rate = recovery.rate %>% round(1) %>%
                         format(nsmall = 1) %>%
                         paste0('%')) %>% DT::datatable(
                           .,
                           rownames = FALSE,
                           #filter = "top",
                           extensions = c('Buttons', 'Scroller'),
                           options = list(
                             dom = 'Blfrtp',
                             bPaginate = TRUE,
                             buttons = c('csv', 'excel'),
                             deferRender = T,
                             scroller = TRUE
                           )
                         ) %>%
  formatStyle(
    'deaths',
    background = styleColorBar(data.latest$deaths, 'red'),
    backgroundSize = '100% 90%',
    backgroundRepeat = 'no-repeat',
    backgroundPosition = 'center'
  ) %>%
  formatStyle(
    'recovered',
    background = styleColorBar(data.latest$recovered, 'green'),
    backgroundSize = '100% 90%',
    backgroundRepeat = 'no-repeat',
    backgroundPosition = 'center'
  ) 

```

Barchart {data-navmenu="World"  data-icon="fa-chart-bar"}
=======================================

### Barchart

```{r, fig.height=10, fig.width=12}

ggplotly(w)
#w
```

Per million people {data-navmenu="World"  data-icon="fa-chart-bar"}
=======================================

### Per million people

```{r, fig.height=6, fig.width=13}

dbz <- db %>% filter(date == max(date), country!="World") %>%
  select(country, pop, date,
         confirmed,
         recovered, deaths) %>%
  mutate(confirmed.pop = (confirmed/pop*1000 %>% round(0)),
         deaths.pop = (deaths/pop*1000 %>% round(0))) 

dbz <- 
  subset(dbz, confirmed>=1)




dfw <- dbz %>% filter(country %in% setdiff(top.countries, c('World', 'Others'))) %>%
  mutate(country=country %>% factor(levels=c(top.countries)))


idx <- order(dfw$confirmed.pop, decreasing = F)
# criar os níveis ordenados
levels <- dfw$country[idx]
# criar um factor com níveis ordenados
dfw$country <- factor(dfw$country, levels=levels, ordered=TRUE)

p1 <- dfw %>% ggplot(aes(x=country, y=confirmed.pop, fill=country)) +
  geom_bar(stat = "identity", position = "dodge") +
  xlab('Country') + ylab('Total confirmed cases of COVID-19 per million people')+
  theme_minimal() +
  theme(legend.title=element_blank(),
        legend.position='none') +
  geom_text(aes(label= round(confirmed.pop,0)),
            vjust = -0.5,
            angle=270,
            color="black",
            position = position_dodge(1),
            size =2.5)+ coord_flip()

idx <- order(dfw$deaths.pop, decreasing = F)
# criar os níveis ordenados
levels <- dfw$country[idx]
# criar um factor com níveis ordenados
dfw$country <- factor(dfw$country, levels=levels, ordered=TRUE)


p2 <- dfw %>% ggplot(aes(x=country, y=deaths.pop, fill=country)) +
  geom_bar(stat = "identity", position = "dodge") +
  xlab('Country') + ylab('Total deaths of COVID-19 per million people')+
  theme_minimal() +
  theme(legend.title=element_blank(),
        legend.position='none',)+
  geom_text(aes(label= round(deaths.pop,1)),
            vjust=-0.5,
            angle=270,
            color="black",
            position = position_dodge(1),
            size =2.5) +  coord_flip()



grid.arrange(p1,p2, ncol=2)



```


```{r, fig.height=7, fig.width=16}

### Cases around the World  

df <- data.long %>% filter(country %in% top.countries) %>%
  mutate(country=country %>% factor(levels=c(top.countries)))
p <- df %>% filter(country != 'World') %>%
  ggplot(aes(x=date, y=count)) + xlab('') + ylab('Count') +
  theme(legend.title=element_blank(),
        legend.text=element_text(size=8),
        legend.key.size=unit(0.5, 'cm'),
        plot.title=element_text(size=11),
        axis.text.x=element_text(angle=45, hjust=1)) +
  facet_wrap(~type, ncol=2, scales='free_y')
## area plot
plot1 <- p + geom_area(aes(fill=country)) +
  labs(title=paste0('Cases around the World - ', max.date.txt))
## line plot and in log scale
# linetypes <- rep(c("solid", "dashed", "dotted"), each=8)
# colors <- rep(c('black', 'blue', 'red', 'green', 'orange', 'purple', 'yellow', 'grey'), 3)
plot2 <- p + geom_line(aes(color=country, linetype=country)) +
  scale_linetype_manual(values=linetypes) +
  scale_color_manual(values=colors) +
  labs(title=paste0('Cases around the World - Log Scale - ', max.date.txt)) +
  scale_y_continuous(trans='log10')

```

Cases around the World - log {data-navmenu="World"  data-icon="fa-chart-line"}
=======================================

### Cases around the World - log

```{r, fig.height=7, fig.width=16}

plot2

```

Cases  {data-orientation=rows data-navmenu="Brazil" data-icon="fa-check"}
=======================================

Row {.tabset .tabset-fade}
---------

### Database  

```{r}

bra <- data %>% arrange((desc(date))) %>% filter(country=='Brazil') 

bra <- subset(bra, confirmed>0)

bra %>% DT::datatable(.,
                      rownames = FALSE, 
                      filter = "top",
                      extensions = c('Buttons', 'Scroller'),
                      options = list(
                        dom = 'Blfrtip',
                        bPaginate = TRUE,
                        buttons = c('csv', 'excel'),
                        deferRender = T,
                        scroller = TRUE)) %>%
  formatStyle(
    'new.deaths',
    background = styleColorBar(bra$new.deaths, 'red'),
    backgroundSize = '100% 90%',
    backgroundRepeat = 'no-repeat',
    backgroundPosition = 'center'
  ) %>%
  formatStyle(
    'new.confirmed',
    background = styleColorBar(bra$new.confirmed, 'orange'),
    backgroundSize = '100% 90%',
    backgroundRepeat = 'no-repeat',
    backgroundPosition = 'center'
  ) 


```

### Graphic

```{r, fig.height=6, fig.width=14, message=F,warning=F}

brz <- data %>% arrange((date)) %>% filter(country=='Brazil') 

brz <- subset(brz, confirmed>0)

bg <- brz %>% dplyr::select(c(country, date, confirmed, deaths, new.confirmed, new.deaths))  %>% gather(key=type, value=count, -c(country, date))



w <- bg  %>% ggplot(aes(x=date, y=count, fill=type)) +
  geom_bar(stat='identity', position = "dodge") +
  #geom_text(aes(label=count, y=count), size=2, vjust=0) +
  xlab('') + ylab('') +
  labs(title=paste0('Brazil - ', max.date.txt)) +
  scale_fill_discrete(name='Type') +
  #scale_y_continuous(labels = scales::percent) +
  theme(legend.title=element_blank(),
        legend.position='none',
        plot.title=element_text(size=11),
        axis.text=element_text(size=7),
        axis.text.x=element_text(angle=45, hjust=1)) +
  facet_wrap(~type, ncol=2, scales='free_y')+
  theme_minimal()
#w
ggplotly(w)
```


Column
------------
### confirmed cases

```{r}

library(flexdashboard)
valueBox(round(max(bra$confirmed),1), icon = "fa-meh", href="#brazil")
```

### deaths

```{r}

valueBox(round(max(bra$deaths),1), icon = "fa-skull")

```

### death rate
```{r}

valueBox(paste(round(max(bra$deaths)/max(bra$confirmed)*100,1)), icon = "fa-percentage")

```


### recovered

```{r}
valueBox(round(max(bra$recovered),1), icon = "fa-heartbeat")

```


### recovery rate

```{r}
valueBox(paste(round(max(bra$recovered)/max(bra$confirmed)*100,1)), icon = "fa-percentage")

```


Map by States {data-orientation=rows data-navmenu="Brazil" data-icon="fa-globe-americas"}
=======================================

### Map by States

```{r, include=F, message=F, warning=F}
#Sys.setlocale(category = "LC_ALL", locale = "Portuguese")

```

```{r, echo=F, warning=F, message=F}
library(stringi)

URL <-paste0("https://pt.wikipedia.org/wiki/Estat%C3%ADsticas_da_pandemia_de_COVID-19_no_Brasil")

tabelas <- read_html(URL) %>% html_table(fill = T)
#names(tabelas[[2]]) <- tabelas[[2]]

dados <- as.data.frame(tabelas[[2]][,-1:-2])

names(dados) <- c("Estado", "Casos Ministério da Saúde", "Casos Secretarias da Saúde","Obitos Ministério da Saúde", "Obitos Secretarias da Saúde")
dados$Estado[[17]] <- "DF"
dados <- dados[1:27,]


dados$`Casos Secretarias da Saúde` <- stri_replace_all_charclass(dados$`Casos Secretarias da Saúde`, "\\p{WHITE_SPACE}", "")
dados$`Casos Ministério da Saúde` <- stri_replace_all_charclass(dados$`Casos Ministério da Saúde`, "\\p{WHITE_SPACE}", "")
dados$`Obitos Ministério da Saúde` <- stri_replace_all_charclass(dados$`Obitos Ministério da Saúde`, "\\p{WHITE_SPACE}", "")
dados$`Obitos Secretarias da Saúde` <- stri_replace_all_charclass(dados$`Obitos Secretarias da Saúde`, "\\p{WHITE_SPACE}", "")







dados$`Casos Secretarias da Saúde` <- parse_number(dados$`Casos Secretarias da Saúde`)
dados$`Casos Ministério da Saúde` <- parse_number(dados$`Casos Ministério da Saúde`)
dados$`Obitos Secretarias da Saúde` <- parse_number(dados$`Obitos Secretarias da Saúde`)
dados$`Obitos Ministério da Saúde` <- parse_number(dados$`Obitos Ministério da Saúde`)


setwd("E:/GIS/Corona")
br <- raster::shapefile("E:/GIS/Corona/BR_Estados.shp")
BR <- as(br, "sf")
names(BR)[5] <- "Estado"
brcorona = merge(BR, dados, by = "Estado")


 library(htmlwidgets)
 library(htmltools)

tag.map.title <- tags$style(HTML("
  .leaflet-control.map-title { 
    transform: translate(-50%,20%);
    position: fixed !important;
    left: 50%;
    text-align: center;
    padding-left: 10px; 
    padding-right: 10px; 
    background: rgba(255,255,255,0.75);
    font-weight: bold;
    font-size: 28px;
  }
"))


library(leaflet)

brcorona_WGS84 <- st_transform(brcorona, 4326)

#pal_fun <- colorQuantile("YlOrRd", NULL, n = 10)
#pal <- colorQuantile("OrRd",NULL,5)
library(RColorBrewer)
darkcols <- brewer.pal(8, "Spectral")

pal <- colorQuantile("YlOrRd", NULL)


pal <- colorBin("YlOrRd", domain = brcorona_WGS84$`Casos Secretarias da Saúde`, 5, pretty = T, alpha = 0.2)

p_popup <- paste0("Número de casos ", brcorona_WGS84$Estado, ": "  , brcorona_WGS84$`Casos Secretarias da Saúde`,"
", "Numero de mortos ", brcorona_WGS84$`Obitos Secretarias da Saúde`) title <- tags$div(tag.map.title, HTML(paste0(sum(brcorona_WGS84$`Casos Secretarias da Saúde`)," casos"))) leaflet(brcorona_WGS84) %>% addPolygons( stroke = FALSE, fillColor = ~ pal(`Casos Secretarias da Saúde`), fillOpacity = 0.8, smoothFactor = 0.5, popup = p_popup ) %>% addTiles() %>% #addControl(title, position = "topleft", className="map-title")%>% addLegend("bottomright", pal = pal, values = ~ `Casos Secretarias da Saúde`, title = 'Número de casos') ``` Map by City {data-orientation=rows data-navmenu="Brazil" data-icon="fa-globe-americas"} ============================ ### Map by City ```{r, echo=F, warning=F, message=F} URL2 <- "https://pt.wikipedia.org/wiki/Estatísticas_da_pandemia_de_COVID-19_no_Brasil" tabelas2 <- read_html(URL2) %>% html_table(.,fill=T, dec = ",") names(tabelas2[[3]]) <- c("Cidade","UF","Casos","Populacao","Casos por Milhão Habitantes") mdados <- as.data.frame(tabelas2[[3]]) mdados$Cidade <- substr(mdados$Cidade, 1, nchar(mdados$Cidade)-3) mdados$Cidade <- gsub(" ", " ", mdados$Cidade) mdados$Casos <- stri_replace_all_charclass(mdados$Casos,"\\p{WHITE_SPACE}", "") mdados$Populacao <- stri_replace_all_charclass(mdados$Populacao,"\\p{WHITE_SPACE}", "") mdados$Casos <- as.numeric(mdados$Casos) mdados$Populacao <- as.numeric(mdados$Populacao) mdados$`Casos por Cem Mil Habitantes` <- mdados$Casos/mdados$Populacao*100000 mdados$`Casos por Cem Mil Habitantes` <- as.numeric(mdados$`Casos por Cem Mil Habitantes`) mdados <- mdados[-5] brm <- raster::shapefile("E:/GIS/Corona/BR_Municipios.shp") BRm <- as(brm, "sf") names(BRm)[2] <- "Cidade" mcorona = merge(BRm, mdados[,c(1,3,5)], by = "Cidade") library(leaflet) mcorona_WGS84 <- st_transform(mcorona, 4326) library(RColorBrewer) darkcols <- brewer.pal(8, "Spectral") bins <- c(0, 10, 50, 100, 500, 1000, Inf) #pal_fun <- colorBin("YlOrRd", domain = mcorona$Casos,5,pretty = T) pal_fun <- colorBin("YlOrRd", domain = mcorona$Casos, 10, pretty = T, alpha = 0.2) #pal_fun <- colorNumeric(darkcols[4:1], NULL) p_popup <- paste0("Número de casos em ", mcorona_WGS84$Cidade, ": " , mcorona_WGS84$Casos) #paste0("Número de casos: ", mcorona_WGS84$casos) leaflet(mcorona_WGS84) %>% addPolygons( stroke = FALSE, fillColor = ~ pal_fun(Casos), fillOpacity = 5, smoothFactor = 0.1, popup = p_popup ) %>% # addHeatmap(lng = ~as.numeric(mcorona_WGS84$LONGITUDE), lat = ~as.numeric(mcorona_WGS84$LATITUDE), intensity = ~Casos, # blur = 10, max = 0.05, radius = 10) %>% addTiles() %>% addLegend("bottomright", pal = pal_fun, values = ~ Casos, title = 'Número de casos') # library(tmap) # tm_shape(mcorona) + # tm_polygons("Casos por Cem Mil Habitantes", # style = "kmeans", # title = "Casos/100 Mil Hab.") + tmap_mode("view") ``` Table by State {data-orientation=rows data-navmenu="Brazil" data-icon="fa-table"} ======================================= ### Table by State ```{r} dados %>% DT::datatable(., rownames = FALSE, filter = "top", extensions = c('Buttons', 'Scroller'), options = list( dom = 'Blfrtip', bPaginate = TRUE, buttons = c('csv', 'excel'), deferRender = T, scroller = TRUE)) ``` Table by City {data-orientation=rows data-navmenu="Brazil" data-icon="fa-table"} ======================================= ### Table by City ```{r} mdados %>% mutate(`Casos por Cem Mil Habitantes` = `Casos por Cem Mil Habitantes` %>% round(1)) %>% DT::datatable(., rownames = FALSE, filter = "top", extensions = c('Buttons', 'Scroller'), options = list( dom = 'Blfrtip', bPaginate = TRUE, buttons = c('csv', 'excel'), deferRender = T, scroller = TRUE)) ``` SIR Model {data-orientation=rows data-navmenu="Brazil" data-icon="fa-exclamation"} ======== Row {.tabset .tabset-fade} --------- ### SIR ```{r} Infectados <- c(brz$confirmed) inicio <- min(brz$date) dia <- 1:(length(Infectados)) Day <- inicio+dia N <- (as.numeric(popz[177,][2])*1000)*0.8 # população do Brasil ``` ```{r, fig.height=6, fig.width=16} old <- par(mfrow = c(1, 2)) plot(Day, Infectados, type = "b") plot(Day, Infectados, log = "y") abline(lm(log10(Infectados) ~ Day)) title("Confirmed Cases 2019-nCoV Brasil", outer = TRUE, line = -2) ``` ### Modelo SIR 2019-nCoV Brasil ```{r, fig.height=6, fig.width=16, message=F,warning=F} par(mfrow = c(1, 2)) SIR <- function(time, state, parameters) { par <- as.list(c(state, parameters)) with(par, { dS <- -beta / N * I * S dI <- beta / N * I * S - gamma * I dR <- gamma * I list(c(dS, dI, dR)) }) } library(deSolve) init <- c(S = N - Infectados[1], I = Infectados[1], R = 0) RSS <- function(parameters) { names(parameters) <- c("beta", "gamma") out <- ode( y = init, times = dia, func = SIR, parms = parameters ) fit <- out[, 3] sum((Infectados - fit) ^ 2) } Opt <- optim( c(0.5, 0.5), RSS, method = "L-BFGS-B", lower = c(0, 0), upper = c(1, 1) ) #Opt$message Opt_par <- setNames(Opt$par, c("beta", "gamma")) #Opt_par t <- 1:300 fit <- data.frame(ode( y = init, times = t, func = SIR, parms = Opt_par )) col <- 1:3 matplot( fit$time, fit[, 2:4], type = "l", xlab = "Day", ylab = "Number of subjects", lwd = 2, lty = 1, col = col ) matplot( fit$time, fit[, 2:4], type = "l", xlab = "Day", ylab = "Number of subjects", lwd = 2, lty = 1, col = col, log = "y" ) points(dia, (Infectados)) legend("bottomright", c("Susceptibles", "Infecteds", "Recovereds"), lty = 1, lwd = 2, col = col, inset = 0.05) title("SIR Model 2019-nCoV Brasil", outer = TRUE, line = -2) par(old) library(benford.analysis) R0 <- setNames(Opt_par["beta"] / Opt_par["gamma"], "R0") ``` ### Methodology A new invisible enemy, only 30kb in size, has emerged and is on a killing spree around the world: 2019-nCoV, the Novel Coronavirus! It has already killed more people than the SARS pandemic and its outbreak has been declared a Public Health Emergency of International Concern (PHEIC) by the World Health Organization (WHO). There are many epidemiological models around, we will use one of the simplest here, the so-called SIR model. We will use this model with the latest data from the current outbreak of 2019-nCoV. There are three groups of people: those that are healthy but susceptible to the disease (S), the infected (I) and the people who have recovered (R): To model the dynamics of the outbreak we need three differential equations, one for the change in each group, where $\beta$ is the parameter that controls the transition between S and I and $\gamma$ which controls the transition between I and R: $${\frac{dS}{dt} = - \frac{\beta I S}{N}}$$ $${\frac{dI}{dt} = \frac{\beta I S}{N}- \gamma I}$$ $${\frac{dR}{dt} = \gamma I}$$ To fit the model to the data we need two things: a solver for differential equations and an optimizer. To solve differential equations the function ode from the *deSolve* package (on CRAN) is an excellent choice, to optimize we will use the optim function from base R. Concretely, we will minimize the sum of the squared differences between the number of infected I at time t and the corresponding number of predicted cases by our model $^{I}$(t): One important number is the so-called basic reproduction number (also basic reproduction ratio) $R_0$ (pronounced “R naught”) which basically shows how many healthy people get infected by a sick person on average: $$R_0 = {\frac{\beta}{\gamma}}$$ So, $R_0$ is `r round(R0,1)`, below the value that many researchers and the WHO give and which is around the same range of SARS, Influenza or Ebola (while transmission of Ebola is via bodily fluids and not airborne droplets). Additionally, according to this model, the height of a possible pandemic would be reached in `r as.Date(inicio+as.numeric(rownames(fit[fit$I == max(fit$I), "I", drop = FALSE]))) %>% format('%d %B')` (`r as.numeric(rownames(fit[fit$I == max(fit$I), "I", drop = FALSE]))` days after it started) with over `r extract.digits(fit[fit$I == max(fit$I), "I", drop = FALSE]$I, number.of.digits = 2)$data.digits` millions brazilians infected and over `r extract.digits(max(fit$I) * max(brz$deaths)/max(brz$confirmed), number.of.digits = 3)$data.digits` thousand dead! **Do not panic!** All of this is preliminary and hopefully (*probably!*) false. When you play along with the above model you will see that the fitted parameters are far from stable. On the one hand, the purpose of this *dashboard* was just to give an illustration of how such analyses are done in general with a very simple (probably too simple!) model, on the other hand, we are in good company here; the renowned scientific journal Nature writes: Researchers are struggling to accurately model the outbreak and predict how it might unfold. On the other hand, I wouldn’t go that far that the numbers are impossibly high. H1N1, also known as swine flu, infected up to 1.5 billion people during 2009/2010 and nearly 600,000 died. And this wasn’t the first pandemic of this proportion in history (think Spanish flu). Yet, this is one of the few times where I hope that my model is wrong and we will all stay healthy! source: [R-bloggers](https://www.r-bloggers.com/epidemiology-how-contagious-is-novel-coronavirus-2019-ncov/) Column {data-width=120} ---------- ### R0 ```{r} library(flexdashboard) valueBox(round(as.numeric(R0),1)) ``` ### infected ```{r} valueBox((round(fit[fit$I == max(fit$I), "I", drop = FALSE]$I,0))) ``` ### peak epidemic date ```{r} valueBox(as.Date(inicio+as.numeric(rownames(fit[fit$I == max(fit$I), "I", drop = FALSE]))) %>% format('%d %B %Y') ) ``` ### death rate ```{r} #valueBox(paste(round((sum(dadz$mortes)/max(dadz$confirmados)*100),1), "%")) valueBox(paste(round((max(brz$deaths)/max(brz$confirmed)*100),1), "%")) ``` ### deaths with current death rate ```{r} #valueBox((round((max(fit$I) * (sum(dadz$mortes)/max(dadz$confirmados))),0))) valueBox((round((max(fit$I) * (max(brz$deaths)/max(brz$confirmed))),0))) ``` Compare {.storyboard data-orientation=rows} ======== ### Cases after first confirmed case ```{r} data.bz <- data %>% arrange(date) %>% filter(country=='Brazil') data.it <- data %>% arrange(date) %>%filter(country=='Italy') data.es <- data %>% arrange(date) %>%filter(country=='Spain') data.us <- data %>% arrange(date) %>%filter(country=='US') data.cn <- data %>% arrange(date) %>%filter(country=='China') data.bz <- subset(data.bz, confirmed>=1) data.bz$n <- 1:length(data.bz$date) data.it <- subset(data.it, confirmed>=1) data.it$n <- 1:length(data.it$date) data.es <- subset(data.es, confirmed>=1) data.es$n <- 1:length(data.es$date) data.us <- subset(data.us, confirmed>=1) data.us$n <- 1:length(data.us$date) data.cn <- subset(data.cn, confirmed>=1) data.cn$n <- 1:length(data.cn$date) linetypes <- rep(c("solid", "dashed", "dotted"), each=8) colors <- rep(c('black', 'red', 'green', 'purple', 'yellow', 'grey'), 3) compz <- rbind(data.bz,data.it,data.es,data.us) dz <- compz d <- max(data.bz$n) qp <- dz %>% ggplot(aes(x=n, y=confirmed, group=country)) + #geom_bar(stat='identity', position = "dodge") + geom_line(aes(color=country, linetype=country)) + geom_vline(xintercept = d, linetype="dotted", color = "orange", size=0.5) + xlab('Days after 1 confirmed cases') + ylab('Total Confirmed') + scale_linetype_manual(values=linetypes) + scale_color_manual(values=colors) + theme(legend.title=element_blank(), legend.text=element_text(size=8), legend.key.size=unit(0.5, 'cm')) #qp ggplotly(qp) #qp2 <- qp + scale_x_log10() + scale_y_log10() #grid.arrange(qp,qp2, ncol=2) ``` *** After `r length(data.bz$date)` days of the first confirmed case in each country Brazil: `r max(data.bz$confirmed)` cases, first case `r min(data.bz$date) %>% format('%d %B %Y')` Italy: `r data.it[data.it$n == max(data.bz$n), "confirmed", drop = FALSE]$confirmed` cases, first case `r min(data.it$date) %>% format('%d %B %Y')` Spain: `r data.es[data.es$n == max(data.bz$n), "confirmed", drop = FALSE]$confirmed` cases, first case `r min(data.es$date) %>% format('%d %B %Y')` US: `r data.us[data.us$n == max(data.bz$n), "confirmed", drop = FALSE]$confirmed` cases, , first case `r min(data.us$date) %>% format('%d %B %Y')` ### Deaths after first confirmed case ```{r} qpz <- dz %>% ggplot(aes(x=n, y=deaths, group=country)) + #geom_bar(stat='identity', position = "dodge") + geom_line(aes(color=country, linetype=country)) + xlab('Days after 1 confirmed cases') + ylab('Total Deaths') + geom_vline(xintercept = d, linetype="dotted", color = "orange", size=0.2) + scale_linetype_manual(values=linetypes) + scale_color_manual(values=colors) + theme(legend.title=element_blank(), legend.text=element_text(size=8), legend.key.size=unit(0.5, 'cm')) #qpz ggplotly(qpz) #qp2 <- qp + scale_x_log10() + scale_y_log10() #grid.arrange(qp,qp2, ncol=2) ``` *** After `r length(data.bz$date)` days of the first confirmed case in each country Brazil: `r max(data.bz$deaths)` deaths, first case `r min(data.bz$date) %>% format('%d %B %Y')` Italy: `r data.it[data.it$n == max(data.bz$n), "deaths", drop = FALSE]$deaths` deaths, first case `r min(data.it$date) %>% format('%d %B %Y')` Spain: `r data.es[data.es$n == max(data.bz$n), "deaths", drop = FALSE]$deaths` deaths, first case `r min(data.es$date) %>% format('%d %B %Y')` US: `r data.us[data.us$n == max(data.bz$n), "deaths", drop = FALSE]$deaths` deaths, , first case `r min(data.us$date) %>% format('%d %B %Y')` ### Recovered after first confirmed case ```{r} qpz <- dz %>% ggplot(aes(x=n, y=recovered, group=country)) + #geom_bar(stat='identity', position = "dodge") + geom_line(aes(color=country, linetype=country)) + xlab('Days after 1 confirmed cases') + ylab('Total Recovered') + scale_linetype_manual(values=linetypes) + geom_vline(xintercept = d, linetype="dotted", color = "orange", size=0.2) + scale_color_manual(values=colors) + theme(legend.title=element_blank(), legend.text=element_text(size=8), legend.key.size=unit(0.5, 'cm')) #qpz ggplotly(qpz) #qp2 <- qp + scale_x_log10() + scale_y_log10() #grid.arrange(qp,qp2, ncol=2) ``` *** After `r length(data.bz$date)` days of the first confirmed case in each country Brazil: `r max(data.bz$recovered)` recovered, first case `r min(data.bz$date) %>% format('%d %B %Y')` Italy: `r data.it[data.it$n == max(data.bz$n), "recovered", drop = FALSE]$recovered` recovered, first case `r min(data.it$date) %>% format('%d %B %Y')` Spain: `r data.es[data.es$n == max(data.bz$n), "recovered", drop = FALSE]$recovered` recovered, first case `r min(data.es$date)%>% format('%d %B %Y')` US: `r data.us[data.us$n == max(data.bz$n), "recovered", drop = FALSE]$recovered` recovered, first case `r min(data.us$date) %>% format('%d %B %Y')` ### Cases after 100 confirmed case ```{r} data.bz <- data %>% arrange(date) %>% filter(country=='Brazil') data.it <- data %>% arrange(date) %>% filter(country=='Italy') data.es <- data %>% arrange(date)%>% filter(country=='Spain') data.gr <- data %>% arrange(date)%>% filter(country=='Germany') #data.ch <- data %>% filter(country=='China') #data.us <- data %>% filter(country=='US') data.bz <- subset(data.bz, confirmed>=100) data.bz$n <- 1:length(data.bz$date) data.it <- subset(data.it, confirmed>=100) data.it$n <- 1:length(data.it$date) data.es <- subset(data.es, confirmed>=100) data.es$n <- 1:length(data.es$date) data.gr <- subset(data.gr, confirmed>=100) data.gr$n <- 1:length(data.gr$date) #data.ch <- subset(data.ch, confirmed>=100) #data.ch$n <- 1:length(data.ch$date) #data.us <- subset(data.us, confirmed>=100) #data.us$n <- 1:length(data.us$date) linetypes <- rep(c("solid","dashed", "dotted"), each=8) colors <- rep(c('black', 'blue', 'red', 'green', 'orange', 'purple', 'yellow', 'grey'), 3) compz <- rbind(data.bz,data.it,data.es,data.gr)#,data.ch,data.us) dz <- compz d <- max(data.bz$n) copt <- compz %>% filter(country!='Brazil') data.co <- copt %>% group_by(n) %>% summarise(country='Sum Without Brazil', confirmed = sum(confirmed, na.rm=T), deaths = sum(deaths, na.rm=T), recovered = sum(recovered, na.rm=T)) data.co$n <- 1:length(data.co$country) compp <- compz %>% select("n","country","confirmed","deaths","recovered") a<-rbind(compp,as.data.frame(data.co)) ab <- subset(a, n < length(data.es$n)-1 ) qp <- ab %>% ggplot(aes(x=n, y=confirmed, group=country)) + #geom_bar(stat='identity', position = "dodge") + geom_line(aes(color=country, linetype=country, )) + #geom_vline(xintercept = d, linetype="dotted", color = "orange", size=0.2) + xlab('Days after 100 confirmed cases') + ylab('Total Confirmed') + scale_linetype_manual(values=linetypes) + scale_color_manual(values=colors) + theme(legend.title=element_blank(), legend.text=element_text(size=8), legend.key.size=unit(0.5, 'cm')) qp1 <- qp + scale_y_log10() + scale_x_log10() # subplot( # style(qp, showlegend = FALSE), # style(qp1, showlegend = T), # nrows =2, margin = 0.05 # ) ggplotly(qp) #qp ``` *** Comparison between Italy, Germany, Spain, and Brazil after the 100th case and the sum of these countries without Brazil Why sum of total cases of these countries? The population of Brazil is similar of the others countries together About ========== Column ---------- ### Curriculum ```{r, fig.height=7.5, fig.width=14, message=F,warning=F} #library(devtools) #devtools::install_github("laresbernardo/lares") library(lares) library(ggplot2) library(extrafont) library(showtext) font_add_google("Open Sans", "open") showtext_auto() plot_timeline2 <- function(event, start, end = start + 1, label = NA, group = NA, title = "Curriculum Vitae Timeline", subtitle = "", size = 7, colour = "orange", save = FALSE, subdir = NA, ...) { df <- data.frame( Role = as.character(event), Place = as.character(label), Start = lubridate::date(start), End = lubridate::date(end), Type = group ) cvlong <- data.frame( pos = rep(as.numeric(rownames(df)), 2), name = rep(as.character(df$Role), 2), type = rep(factor(df$Type, ordered = TRUE), 2), where = rep(as.character(df$Place), 2), value = c(df$Start, df$End), label_pos = rep(df$Start + floor((df$End - df$Start) / 2), 2) ) maxdate <- max(df$End) p <- ggplot(cvlong, aes( x = value, y = reorder(name, -pos), label = where, group = pos )) + geom_vline(xintercept = maxdate, alpha = 0.8, linetype = "dotted") + labs( title = title, subtitle = subtitle, x = NULL, y = NULL, colour = NULL ) + lares::theme_lares() + theme( panel.background = element_rect(fill = "white", colour = NA), axis.ticks = element_blank(), panel.grid.major.x = element_line(size = 0.25, colour = "grey80") ) if (!is.na(cvlong$type)[1] | length(unique(cvlong$type)) > 1) { p <- p + geom_line(aes(color = type), size = size) + facet_grid(type ~ ., scales = "free", space = "free") + guides(colour = "none") + scale_colour_hue() } else { p <- p + geom_line(size = size, colour = colour) } p <- p + geom_label( aes(x = label_pos), colour = "black", size = 2.5, alpha = 0.3 ) if (save) { file_name <- "cv_timeline.png" if (!is.na(subdir)) { dir.create(file.path(getwd(), subdir), recursive = T) file_name <- paste(subdir, file_name, sep = "/") } p <- p + ggsave(file_name, width = 8, height = 6) message(paste("Saved plot as", file_name)) } return(p) } order <- c("Role", "Place", "Type", "Start", "End") today <- as.character(Sys.Date()) ### # cv <- data.frame(rbind( # # c("BSc in Agronomy", "UESC", "Academic", "2015-07-19", "2020-01-27"), # c("Tech in OHS", "IFBA", "Academic", "2012-01-01", "2014-03-01"), # c("Agronomist Intern", "MARS", "Work Experience", "2019-09-23", "2019-12-20"), # c("Agronomist Intern", "CEPLAC", "Work Experience", "2017-06-01", "2018-07-01"), # c("Telecom Technical", "CSM Telecom", "Work Experience", "2005-04-01", "2010-07-01"), # c("Technical Manager", "CSM Telecom", "Work Experience", "2010-07-01", "2015-07-01"), # c("Telecom Technical", "TeleData", "Work Experience", "2002-06-01", "2004-02-01"), # c("Tech in OHS Intern", "SETMA", "Work Experience", "2013-12-01", "2014-02-01"), # c("Intern", "BitWay", "Work Experience", "2001-03-01", "2001-09-01"), # c("R Language", "Advanced", "Skills", "2016-01-01", today), # c("ArcGIS", "Intermediate", "Skills", "2016-01-01", today), # c("Excel", "Advanced", "Skills", "2000-01-01", today), # c("Power BI", "Intermediate", "Skills", "2018-01-01", today), # c("Web Developer", "Ação Ilhéus", "Voluntary", "2008-01-01", "2012-01-01"), # c("Intern", "NUPER", "Voluntary", "2017-05-01", "2018-04-01"))) # # ### # # colnames(cv) <- order # colour <- c("red", "blue", "green") # # plot_timeline2( # event = cv$Role, # start = cv$Start, # end = cv$End, # label = cv$Place, # group = cv$Type, # save = FALSE, # subtitle = "Cid Edson Póvoas" # ) # cv <- data.frame(rbind( c("BSc in Agronomy", "UESC", "Academic", "2015-07-19", "2020-01-27"), c("Tech in OHS", "IFBA", "Academic", "2012-01-01", "2014-03-01"), c("Agronomist - Data Scientist", "ANOVAGRO", "Work Experience", "2021-09-29", today), c("Data Analyst", "Consult & Agro", "Work Experience", "2020-02-17", "2021-09-28"), c("Agronomist Intern", "MARS", "Work Experience", "2019-09-23", "2019-12-20"), c("Agronomist Intern", "CEPLAC", "Work Experience", "2017-06-01", "2018-07-01"), c("Telecom Technical", "CSM Telecom", "Work Experience", "2005-04-01", "2010-07-01"), c("Tech in OHS Intern", "SETMA", "Work Experience", "2013-12-01", "2014-02-01"), c("Technical Manager", "CSM Telecom", "Work Experience", "2010-07-01", "2015-07-01"), c("Telecom Technical", "TeleData", "Work Experience", "2002-06-01", "2004-02-01"), c("Intern", "BitWay", "Work Experience", "2001-03-01", "2001-09-01"), c("R Language", "Advanced", "Skills", "2016-01-01", today), c("ArcGIS", "Intermediate", "Skills", "2016-01-01", today), c("Excel", "Advanced", "Skills", "2000-01-01", today), c("Power BI", "Intermediate", "Skills", "2018-01-01", today), c("Web Developer", "Ação Ilhéus", "Voluntary", "2008-01-01", "2012-01-01"), c("Intern", "NUPER", "Voluntary", "2017-05-01", "2018-04-01"))) ### colnames(cv) <- order colour <- c("red", "blue", "green") a<- plot_timeline2( event = cv$Role, start = cv$Start, end = cv$End, label = cv$Place, group = cv$Type, save = FALSE, subtitle = "Cid Edson Póvoas" ) a ```