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

### "Josephs" Data from Lab 4

```{r, message = FALSE}
library(mdsr)
library(ggthemes)
BabynamesDist <- make_babynames_dist()
Josephs <- filter(BabynamesDist, name == "Joseph" & sex == "M")
```

### Displaying data tables interactively

If we want to browse the data itself in a searchable, pageable format, we can use the `DT` package:

```{r}
library(DT)
## CAUTION: Don't do this with ginormous datasets
## datatable(BabynamesDist, options = list(pageLength = 25))
datatable(Josephs, options = list(pageLength = 10))
```

### Recreating the plot from Lab 4

```{r, message = FALSE, fig.width = 8, fig.height = 4}
median.birthyear <- 
  with(
     Josephs, 
     Hmisc::wtd.quantile(
         x = year, 
         weights = est_alive_today,
         prob = 0.5)
  )
joseph_plot <- Josephs %>%
  ggplot(aes(
    x = year)) +
  geom_bar(
    stat = "identity",
    aes(y = est_alive_today / 1000),
    fill = "#b2d7e9", color = "white") +
  geom_line(aes(y = count_thousands)) +
  xlab("Birth Year") + 
  ylab("Number of People (Thousands)") +
  geom_bar(
    stat = "identity",
      aes(
        y = ifelse(
          year == median.birthyear, # the condition 
          est_alive_today / 1000,   # value if true
          0                         # value if false
          )),                      
        fill = "#008fd5", # the darker blue color
        color = "white") +
  theme_fivethirtyeight() +
  ggtitle("Age Distribution of American Boys Named Joseph") +     
  geom_text(
    x = 1935, y = 30, 
    label = "Number of Josephs\nborn each year"
    ) +
  geom_text(
    x = 1915, y = 13, 
    label = "Number of Josephs\nborn each year\nestimated to be alive\non 1/1/2014", 
    colour = "#b2d7e9"
    ) +
  geom_text(
    x = 2003, y = 40, 
    label = "The median\nliving Joseph\n in 2014 was 37 years old",
    colour = "darkgray"
    ) + 
  geom_curve(
    x = 1995, xend = 1974, y = 40, yend = 24,
    arrow = arrow(length = unit(0.3, "cm")), 
    curvature = 0.5
    ) +   
  ylim(0, 42)
joseph_plot  
```

### Making it interactive with `plotly`

```{r, message = FALSE, warning = FALSE, fig.width = 8, fig.height = 5}
library(plotly)
ggplotly(joseph_plot)
```

Not all visual properties are rendered properly (font is different, arrows are missing), and the mouseover text is not especially clean, but it's a rudimentary interactive plot that didn't require any customization.

### `ggvis`: Customizeable Mouseover

To customize what is displayed when we hover over some data, we can write a custom function and use the `ggvis` package.

This package is in a "beta" state, and currently
can't display interactive plots in knitted HTML.

### Creating Shiny Applets

See separate files