Table

Table

Bar-chart

## Column

Vertical

Horizontal

Lollipop

Donut-chart

## Row

Simple

GDP

Scatter and Line Chart

Donut and Scatter Chart

Drug

Epidemic of Drug Overdose

Oil

Upper X-axist Line-Chart

Lower X-axist Line-Chart

---
title: "Flex Dashboards"
output: 
  flexdashboard::flex_dashboard:
    vertical_layout: scroll
    theme: yeti
    source_code: embed
---

```{r setup, include=FALSE}
# Importing libraries
library(flexdashboard)
library(tidyverse)
library(highcharter)
library(gt)
library(htmltools)
library(viridis)
library(DT)
```


```{r}
# Importing data
df <- read_csv('bestsellers with categories.csv')

# Removing duplicates
df <- df %>% 
  distinct(Name, .keep_all = TRUE) %>% 
  rename(User_Rating = 'User Rating')
```


Table {data-orientation=rows}
=======================================================================

### Table {data-height=520}

```{r}
# This is going to be a datatable
df1 <- df %>% 
  filter(User_Rating >= 4.5) %>% 
  arrange(desc(Reviews)) %>% 
  select(Name, Author,User_Rating,Reviews,Price,Year)

datatable(df1, 
          options=list(scrollX=TRUE),
          caption = htmltools::tags$caption(
    style = 'caption-side: bottom; text-align: center;',
    'Table: ', htmltools::em('Best Books from 2009 to 2019 By Users Rating Greateher Than 4.5.')
  ))
```

Bar-chart {data-orientation=rows}
=======================================================================


## Column {.tabset .tabset-fade data-height=520}
-----------------------------------------------------------------------

### Vertical {data-width=1200}

```{r fig.height=5}
# Colors
custom_colors <- viridis::turbo(n = 15)

# Most popular authors by reviews
df %>% 
  group_by(Author) %>% 
  summarise(Reviews = sum(Reviews)) %>% 
  arrange(desc(Reviews)) %>% 
  head(15) %>% 
  hchart('column', hcaes(x = Author, y = Reviews,color = custom_colors)) %>%   hc_add_theme(hc_theme_google()) %>% 
  hc_tooltip(pointFormat = '<b>Number of Reviews: </b> {point.y} <br>') %>% 
  hc_title(text = 'Most Popular Authors from 2009 to 2019',
           style = list(fontSize = '25px', fontWeight = 'bold')) %>% 
  hc_subtitle(text = 'By Number of Reviews',
              style = list(fontSize = '16px')) %>% 
  hc_credits(enabled = TRUE, text = '@dsciencelabs')
  

```

### Horizontal {data-width=1200}

```{r fig.height=5}
# Colors
custom_colors <- viridis::plasma(n = 15)

# Most popular books by reviews
df %>% 
  arrange(desc(Reviews)) %>% 
  head(15) %>% 
  hchart('bar', hcaes(x = Name, y = Reviews, color = custom_colors)) %>% 
  hc_add_theme(hc_theme_google()) %>% 
  hc_tooltip(pointFormat = '<b>Number of Reviews: </b> {point.y} <br>') %>% 
  hc_title(text = 'Most Popular Books from 2009 to 2019',
           style = list(fontSize = '25px', fontWeight = 'bold')) %>% 
  hc_subtitle(text = 'By Number of Reviews',
              style = list(fontSize = '16px')) %>% 
  hc_credits(enabled = TRUE, text = '@dsciencelabs')
```


### Lollipop {data-width=600 data-height=510}

```{r fig.height=5}
# Importing second data
data <- read_csv('charts.csv')

data <- data %>% 
  rename(weeks_on_board = 'weeks-on-board',
         peak_rank = 'peak-rank') %>% 
  select(-'last-week')

# Removing duplicates and select the max value
data1 <- data %>% 
  group_by(song, artist) %>% 
  summarise(weeks_on_board = max(weeks_on_board))

# Colors
custom_colors <- viridis::mako(n = 20)

# Most popular songs by weeks on board
data1 %>% 
  arrange(desc(weeks_on_board)) %>% 
  head(20) %>% 
  hchart('lollipop', hcaes(x = song, y = weeks_on_board, color = custom_colors)) %>% 
  hc_add_theme(hc_theme_google()) %>% 
  hc_tooltip(pointFormat = '<b>Number of Weeks on Board: </b> {point.y} <br>') %>% 
  hc_yAxis(title = list(text = 'Weeks on Board')) %>% 
  hc_xAxis(title = list(text = 'Songs')) %>% 
  hc_title(text = 'Most Popular Songs',
           style = list(fontSize = '25px', fontWeight = 'bold')) %>% 
  hc_subtitle(text = 'By Number of Weeks on Board',
              style = list(fontSize = '16px')) %>% 
  hc_credits(enabled = TRUE, text = '@dsciencelabs')
```


Donut-chart {data-orientation=rows}
=======================================================================

## Row  
-----------------------------------------------------------------------

### Simple {data-width=600 data-height=510}

```{r fig.height=5}
# Colors
custom_colors <- viridis::inferno(n = 10)

# Most popular artists by weeks on board
data1 %>% 
  group_by(artist) %>% 
  summarise(weeks_on_board = sum(weeks_on_board)) %>% 
  arrange(desc(weeks_on_board)) %>% 
  head(10) %>% 
  hchart('pie', hcaes(x = artist, y = weeks_on_board, color = custom_colors),innerSize = 200) %>% 
  hc_add_theme(hc_theme_google()) %>% 
  hc_tooltip(pointFormat = '<b>Number of Weeks on Board: </b> {point.y} <br>') %>% 
  hc_title(text = 'Most Popular Artists',
           style = list(fontSize = '25px', fontWeight = 'bold')) %>% 
  hc_subtitle(text = 'By Number of Weeks on Board',
              style = list(fontSize = '16px')) %>% 
  hc_credits(enabled = TRUE, text = '@dsciencelabs')
```


GDP {data-orientation=rows}
=======================================================================

### Scatter and Line Chart {data-width=600 data-height=510}

```{r fig.height=5}
library(tidyverse)
library(gapminder)
data(gapminder, package = "gapminder")

gp <- gapminder %>%
  arrange(desc(year)) %>%
  distinct(country, .keep_all = TRUE)

gp2 <- gapminder %>%
  select(country, year, pop) %>% 
  nest(-country) %>%
  mutate(
    data = map(data, mutate_mapping, hcaes(x = year, y = pop), drop = TRUE),
    data = map(data, list_parse)
    ) %>%
  rename(ttdata = data)

gptot <- left_join(gp, gp2, by = "country")

hchart(gptot, "point",
  hcaes(lifeExp, 
        gdpPercap, 
        name = country, 
        size = pop, 
        group = continent)) %>%
  hc_yAxis(type = "logarithmic") %>% 
  # here is the magic (inside the function)
  hc_tooltip(
    useHTML = TRUE,
    headerFormat = "<b>{point.key}</b>",
    pointFormatter = tooltip_chart(accesor = "ttdata")
  )
```

### Donut and Scatter Chart {data-width=600 data-height=510}

```{r}
donutdata <- gp %>% 
  group_by(continent) %>% 
  summarise(pop = sum(pop/1e6)*1e6)

donutdata2 <- gp %>% 
  select(continent, lifeExp, gdpPercap) %>% 
  nest(-continent) %>% 
  mutate(
    data = map(data, mutate_mapping, hcaes(x = lifeExp, y = gdpPercap), drop = TRUE),
    data = map(data, list_parse)
    ) %>%
  rename(ttdata = data) %>% 
  left_join(donutdata)

hc <- hchart(
  donutdata2,
  "pie",
  hcaes(name = continent, y = pop),
  innerSize = 300, 
  color=viridis::inferno(n = 15)
  )

hc %>% 
  hc_tooltip(
    useHTML = TRUE,
    headerFormat = "<b>{point.key}</b>",
    pointFormatter = tooltip_chart(
      accesor = "ttdata",
      hc_opts = list(
        chart = list(type = "scatter"),
        credits = list(enabled = FALSE),
        plotOptions = list(scatter = list(marker = list(radius = 2)))
        ),
      height = 130
      ),
    positioner = JS(
      "function () {
      
        /* one of the most important parts! */
        xp =  this.chart.chartWidth/2 - this.label.width/2
        yp =  this.chart.chartHeight/2 - this.label.height/2
      
        return { x: xp, y: yp };
      
      }"),
    shadow = FALSE,
    borderWidth = 0,
    backgroundColor = "transparent",
    hideDelay = 1000
    )
```

Drug {data-orientation=rows}
=======================================================================

### Epidemic of Drug Overdose {data-width=600 data-height=510}

```{r}
library(jsonlite)
library(dplyr)
library(tidyr)
library(highcharter)

URL <- "http://graphics8.nytimes.com/newsgraphics/2016/01/15/drug-deaths/c23ba79c9c9599a103a8d60e2329be1a9b7d6994/data.json"

data("uscountygeojson")
data("unemployment")

data <-  fromJSON(URL) %>% 
  tbl_df() %>% 
  gather(year, value, -fips) %>% 
  mutate(year = sub("^y", "", year),
         value = ifelse(is.na(value), 0, value))



ds <- data %>% 
  group_by(fips) %>% 
  do(item = list(
    fips = first(.$fips),
    sequence = .$value,
    value = first(.$value))) %>% 
  .$item

hc <- highchart(type = "map") %>% 
  hc_add_series(
    data = ds,
    name = "drug deaths per 100,000",
    mapData = uscountygeojson,
    joinBy = "fips",
    borderWidth = 0.01
    ) %>% 
  hc_colorAxis(stops = color_stops()) %>%  
  hc_title(text = "How the Epidemic of Drug Overdose Deaths Ripples") %>% 
  hc_subtitle(text = "Overdose deaths per 100,000") %>% 
  hc_legend(
    layout = "horizontal",
    reversed = TRUE,
    floating = TRUE,
    align = "right"
    ) %>% 
  hc_motion(
    enabled = TRUE,
    axisLabel = "year",
    labels = sort(unique(data$year)),
    series = 0,
    updateIterval = 50,
    magnet = list(
      round = "floor",
      step = 0.1
    )
  ) %>% 
  hc_chart(marginBottom  = 100)

hc
```

Oil {data-orientation=rows}
=======================================================================

### Upper X-axist Line-Chart {data-width=600 data-height=510}

```{r}
library(tidyverse) 
library(jsonlite)

json <- read_lines("https://ourworldindata.org/wp-content/uploads/nvd3/nvd3_multiBarChart_Oil/multiBarChart_Oil.html")
json <- json[seq(
  which(str_detect(json, "var xxx")),
  first(which(str_detect(json, "\\}\\]\\;")))
)]

json <- fromJSON(str_replace_all(json, "var xxx = |;$", ""))
json <- transpose(json)

# convert list to a dataframe
dspills <- map_df(json, function(x) {
  df <- as.data.frame(x[["values"]])
  df$key <- x[["key"]]
  tbl_df(df)
  df
})


# Create a chart
hcspills <- hchart(dspills, "areaspline", hcaes(x, y, group = "key")) %>% 
  hc_plotOptions(series = list(stacking = "normal")) %>% 
  hc_xAxis(type = "datetime") %>% 
  hc_title(text = "Number of Oil Spills Over the Past 4 Decades")%>% 
  hc_chart(
    divBackgroundImage="https://aceiteweb.com/wp-content/uploads/2018/06/aceite.jpg",
    backgroundColor = hex_to_rgba("white", 0.90)
  )

hcspills
```

### Lower X-axist Line-Chart {data-width=600 data-height=510}

```{r}
hcspills2 <- hcspills %>% 
  hc_colors(c("#000000", "#222222")) %>% 
  hc_title(align = "left", style = list(color = "black")) %>% 
  hc_plotOptions(series = list(marker = list(enabled = FALSE))) %>% 
  hc_tooltip(sort = TRUE, table = TRUE) %>% 
  hc_legend(align = "right", verticalAlign = "top", layout = "horizontal") %>% 
  hc_credits(
    enabled = TRUE,
    text = "Data from ITOPF.com",
    href = "http://www.itopf.com/knowledge-resources/data-statistics/statistics/"
  ) %>% 
  hc_chart(
    divBackgroundImage = "https://t4.ftcdn.net/jpg/02/39/60/81/360_F_239608136_4qtLPCPhCCzNaSoPo2hiEfMFA1fBXa2R.jpg",
    backgroundColor = hex_to_rgba("white", 0.70)
  ) %>% 
  hc_xAxis(
    opposite = TRUE,
    gridLineWidth = 0,
    title = list(text = "Time", style = list(color = "black")),
    lineColor = "black", tickColor = "black",
    labels = list(style = list(color = "black"))
    ) %>% 
  hc_yAxis(
    reversed = TRUE, 
    gridLineWidth = 0, 
    lineWidth = 1,
    lineColor = "black",
    tickWidth = 1,
    tickLength = 10, 
    tickColor = "black",
    title = list(text = "Oil Spills", style = list(color = "black")),
    labels = list(style = list(color = "black"))
    ) %>% 
  hc_add_theme(hc_theme_elementary())

hcspills2
```