---
title: "Live Code for Day 2"
author: "Dave Armstrong"
date: "5/28/2020"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, message=FALSE, warning=FALSE)
```

```{r, eval=FALSE}
load("~/Dropbox/Interactive_Viz/deck2/counties_covid.rda")
ohio <- counties_covid %>% filter(state == "Ohio")
save(ohio, file="ohio_covid.rda")
```

```{r}
load("ohio_covid.rda")
```


```{r}
library(carData)
data(Prestige)

library(plotly)

Prestige <- Prestige %>% 
  mutate(text = paste0(
            "Occupation: ", rownames(Prestige), 
            "\nEducation: ", education, 
            "\nPrestige: ", prestige))



plot_ly(Prestige, x=~education, y=~prestige)
p <- plot_ly(Prestige, x=~education, y=~prestige, color=~type, 
        text = ~text, hoverinfo="text", 
        type="scatter", mode="markers") %>% 
  layout(
    xaxis = list(title="Average Years of Education") , 
    yaxis=list(title="Occupational Prestige")
  )
p
```


```{r, eval=FALSE}
library(htmltools)
saveWidget(p, file="ed_pres.html")
saveWidget(p, file="ed_pres2.html", selfcontained = FALSE, libdir="eplibs")
```

```{r}
library(crosstalk)

sharedPrestige <- SharedData$new(Prestige)



plot1 <- plot_ly(sharedPrestige, x=~education, y=~prestige, color=~type, 
        text = ~text, hoverinfo="text", 
        type="scatter", mode="markers") %>% 
  layout(
    xaxis = list(title="Average Years of Education") , 
    yaxis=list(title="Occupational Prestige")
  )

plot2 <- plot_ly(sharedPrestige, x=~income, y=~women, color=~type,
        type="scatter", mode="markers") %>% 
  layout(
    xaxis = list(title="Average % Women Incumbents") , 
    yaxis=list(title="Income")
  )
#bscols(widths=c(6,6), 
plot1
plot2
#)

```


```{r}
mod <- lm(prestige ~ income + education, data=Prestige)
```

The effect of income on prestige is `r round(coef(mod)[2], 3)`


Here is the mean of a random normal variable with 100 observations `r round(mean(rnorm(100)), 2)`, `r sprintf("%.2f", mean(rnorm(100)))`. 



# knitting the parameterized dashboard

```{r}
rmarkdown::render("covid_dashboard_param.Rmd", 
  params = list(state = "Maine")
)
```


```{r}
setwd("~/Dropbox/Interactive_Viz")
load("counties_covid.rda")
## find all of the states in the dataset 
# states <- unique(na.omit(counties_covid$state) )
states <- c("Maine", "Michigan", "Wisconsin", "Maryland")
 for(i in 1:length(states)){
 rmarkdown::render("covid_dashboard_param.Rmd",
   params = list(state = states[i]),
   output_file = paste0(states[i], " COVID-19 Dashboard")
 )
 }
```



```{r}
library(ggplot2)
data(diamonds)
clarities <- sort(unique(diamonds$clarity))

for(i in 1:length(clarities)){
  rmarkdown::render(normalizePath("~/Dropbox/Interactive_Viz/deck2/deck2-apps/01-diamonds-dashboard/02-diamonds-dashboard_param.Rmd"), 
                    params=list(clarity = clarities[i]), 
                    output_file = paste0(clarities[i], " Diamond Dashboard"))
  
}
```


# states covid animation

```{r}
load("states_covid.rda")
# dates <- as.Date(c("01-26-2020", "05-21-2020"), format="%m-%d-%Y")
# alldates <- seq(dates[1], dates[2], by="day")
# date_num <- seq_along(alldates)
# week_num <- (date_num-1) %/% 7
# df <- data.frame(date=alldates, week_num=week_num)
# states2 <- left_join(states_covid, df)

states_covid %>% 
  group_by(STATE_NAME, week, SUB_REGION) %>% 
  summarise(deaths = max(deaths), cases=max(cases)) %>% 
plot_ly( x=~cases, y=~deaths, frame=~week, color=~SUB_REGION, 
        type="scatter", mode="markers")




```


```{r}

library(crosstalk)
states <- states_covid %>% as.data.frame %>% select(week, STATE_NAME, SUB_REGION, deaths,cases)

states_week <- states %>% 
  group_by(STATE_NAME, week, SUB_REGION) %>% 
  summarise(deaths = max(deaths), cases=max(cases)) 

shareStates <- SharedData$new(states_week)

bscols(widths=c(3,9),   
      filter_select("st", "State", shareStates, ~STATE_NAME, multiple=TRUE),
      plot_ly(shareStates, x=~cases, y=~deaths, frame=~week, color=~SUB_REGION,
       type="scatter", mode="markers")
)
```

## Animate 1-D plots

```{r}
library(gapminder)
gapminder %>% mutate(gdpcat =DAMisc::binVar(gdpPercap, 5, method = "proportions")) %>%
  group_by(gdpcat, year) %>% 
  summarise(count=n()) %>%
  plot_ly(x=~gdpcat, y=~count, frame=~year) %>% 
  add_bars()
```



## functions
```{r}
x <- 1
fun <- function(x=4){
  x
}
fun(3)
x
fun(1)
```


## shiny app histogram

```{r}
library(shiny)
library(ggplot2)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      numericInput(
        inputId="nbins",
        label="Number of Bins",
        value=10,
        min=1,
#        max=30,
        width='100px')
    ), 
    mainPanel(
      plotOutput(
        "histo",
        width="100%"
      )
    )
  )  
)

server <- function(input, output, session) {
  mydf <- data.frame(x= rnorm(100))
  output$histo <- renderPlot({
    ggplot(mydf, aes(x=x)) +
      geom_histogram(bins=input$nbins) +
      theme_minimal()
  })
}

shinyApp(ui, server)

```

## app with reactive data.

```{r}
library(shiny)
library(ggplot2)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      numericInput(
        inputId="nbins",
        label="Number of Bins",
        value=10,
        min=1,
#        max=30,
        width='100px'),
      numericInput(
        inputId="nObs", 
        label = "Number of Observations", 
        value = 100, 
        min = 10, 
        max = 10000
      )
    ), 
    mainPanel(
      plotOutput(
        "histo",
        width="100%"
      )
    )
  )  
)

server <- function(input, output, session) {

  mydf <- reactive({
    data.frame(x= rnorm(input$nObs))
  })
  
  output$histo <- renderPlot({
    ggplot(mydf(), aes(x=x)) +
      geom_histogram(bins=input$nbins) +
      theme_minimal()
  })
}

shinyApp(ui, server)

```

## app with distributions

```{r}
ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      numericInput(
        inputId="nbins",
        label="Number of Bins",
        value=10,
        min=1,
#        max=30,
        width='100px'),
      numericInput(
        inputId="nObs", 
        label = "Number of Observations", 
        value = 100, 
        min = 10, 
        max = 10000
      ), 
      radioButtons(
        inputId = "dist", 
        label = "Distribution", 
        choices = c("Normal"="norm", 
                    "Chi-squared(3)"="chi2", 
                    "F(2,10)" = "fdist", 
                    "Uniform(-3,3)" = "unif")
          ),
      checkboxInput(
        inputId = "lineOn", 
        label="Theoretical Distribution Line", 
        value=TRUE
      )
    ), 
    mainPanel(
      plotOutput(
        "histo",
        width="100%"
      )
    )
  )  
)

server <- function(input, output, session) {

  mydf <- reactive({
    x <- switch(input$dist, 
                "norm" = rnorm(input$nObs), 
                "chi2" = rchisq(input$nObs, 3), 
                "fdist" = rf(input$nObs, 2, 10), 
                "unif" = runif(input$nObs, -3,3))
    data.frame(x=x)
  })
  
  theo.df <- reactive({
    s <- seq(min(mydf()$x), max(mydf()$x), length=250)
    y.theoretical <- switch(input$dist, 
                "norm" = dnorm(s), 
                "chi2" = dchisq(s, 3), 
                "fdist" = df(s, 2, 10), 
                "unif" = dunif(s, -3,3))
    data.frame(x=s, y=y.theoretical)
  })  
  
  
  
  
  output$histo <- renderPlot({
    ggplot() +
      geom_histogram(data=mydf(), aes(x=x), bins=input$nbins) +
      geom_line(data=theo.df(), aes(x=x, y=y), color="red") + 
      theme_minimal()
  })
}
```


## shiny app with 4 state selector


```{r}
library(shinydashboard)
library(plotly)
library(htmltools)
source("../full_height_box.r")
ui <- dashboardPage(
  dashboardHeader(title="COVID-19 Dashboard"),
  dashboardSidebar(
    selectInput(
      inputId = "inpState", 
      label = "Choose a State", 
      choices=c("Maine", "Maryland", "Michigan", "Wisconsin"), 
      width="200px")
  ),
  dashboardBody(
    fluidRow(
      column(width=7, 
             box(id="map-container", title="Map of COVID-19 Cases", plotlyOutput("map"), width=NULL)
      ), 
      column(width=5, 
             box(title="COVID-19 Cases by Republican Vote", plotlyOutput("scatter"), width=NULL), 
             box(title="Data", DT::dataTableOutput("tab"), width=NULL)
      )
    )
  ),
  full_height_box("map-container", "map"),
)

server <- function(input, output){
  library(ggplot2)
  library(dplyr)
  library(plotly)
  library(DT)
  library(rio)
  library(sf)
  library(stringr)
  library(crosstalk)
  library(d3scatter)
  library(htmltools)
  library(plotly)
  load("counties_covid.rda")
  #inpstate <- "Ohio"

  tmp <- reactive({counties_covid %>% 
      filter(state == input$inpState) %>% 
      select(NAMELSAD, st, cases, repvote, geometry) %>% 
      mutate(text = paste(NAMELSAD, "\n", cases, " cases", sep=""), 
             repvote = repvote*100)
  })
  
  output$map <- renderPlotly({
    plot_ly(tmp(), split = ~ text,  color = ~log(cases),  alpha = 1, 
             hoverinfo="text", hoveron="fill", showlegend=FALSE)
  })
  
  output$scatter  <- renderPlotly({
    plot_ly(tmp(), x=~repvote, y=~cases, width="100%", type="scatter", height=300) %>% 
      add_markers() %>%
      layout(xaxis=list(title="Republican Vote"),
             yaxis=list(title="Number of COVID-19 Cases"))
  })

  output$tab <- DT::renderDataTable({
    tmp() %>% 
      datatable(extensions="Scroller", class="compact",
                colnames = c("County", "State", "# Cases", "Republican\nVote"), 
                rownames=FALSE, 
                options = list(paging=FALSE, pageLength = 20, scrollY = "350px",
                               columnDefs = list(list(className = 'dt-center', 
                                                      targets = 0:3), 
                                                 list(visible=FALSE, targets=c(4,5))))) %>% 
      formatRound(columns = "repvote", digits=0)
  })
  
  
     
}

shinyApp(ui,server)

```

## shiny with two rows

```{r}

ui <- dashboardPage(
  dashboardHeader(title="COVID-19 Dashboard"),
  dashboardSidebar(
      uiOutput("state_selector")
    ),
  dashboardBody(
    fluidRow(
      column(width=6, 
             box(title="Map of COVID-19 Cases", plotlyOutput("map"), width=NULL),
      ), 
      column(width=6, 
             box(title="COVID-19 Cases by Republican Vote", plotlyOutput("scatter"), width=NULL)
      )
    ),
    fluidRow( 
     column(width=2),
     column(width=8, 
             box(title="Data", DT::dataTableOutput("tab"), width=NULL), 
     column(width=2)
      )
    )
  ),
#  full_height_box("map-container", "map"),
)
```

```{r}


