---
title: "simplevis"
author: "David Hodge"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{simplevis}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

```{r, message=FALSE, warning=FALSE}
library(dplyr)
library(simplevis)
```

### Purpose 

`simplevis` is a package of wrapper functions to make 'ggplot2' and 'leaflet' visualisation easier and prettier.

### simplevis ggplot graph types

`simplevis` provides the following types of `ggplot`:

* horizontal bar
* vertical bar
* line plot 
* point plot
* boxplot

For each ggplot type, 4 functions are available.

1. A `ggplot` <i>not</i> coloured or faceted (e.g. `ggplot_hbar`)
```{r, message = FALSE, warning = FALSE, fig.height = 3, fig.width = 6}
plot_data <- ggplot2::diamonds %>%
  mutate(cut = stringr::str_to_sentence(cut)) %>%
  group_by(cut) %>%
  summarise(average_price = mean(price)) %>%
  mutate(average_price = round(average_price / 1000, 1)) %>%
  mutate(cut = factor(cut, levels = c("Fair", "Good", "Very good", "Premium", "Ideal"))) 

ggplot_hbar(plot_data, average_price, cut,
            title = "Average diamond price by cut", 
            x_title = "Average price ($US thousands)", 
            y_title = "Cut")

```

2. A `ggplot` coloured, but not faceted (e.g. `ggplot_hbar_col`)
```{r, message = FALSE, warning = FALSE, fig.height = 4, fig.width = 6}
plot_data <- ggplot2::diamonds %>%
  mutate(cut = stringr::str_to_sentence(cut)) %>%
  group_by(cut, clarity) %>%
  summarise(average_price = mean(price)) %>%
  mutate(average_price = round(average_price / 1000, 1))

ggplot_hbar_col(plot_data, average_price, cut, clarity, 
                title = "Average diamond price by cut and clarity", 
                x_title = "Average price ($US thousands)", 
                y_title = "Cut")

```

3. A `ggplot` facetted, but not coloured (e.g. `ggplot_hbar_facet`)
```{r, message = FALSE, warning = FALSE, fig.height = 4, fig.width = 7}
plot_data <- ggplot2::diamonds %>%
  mutate(cut = stringr::str_to_sentence(cut)) %>%
  group_by(cut, clarity) %>%
  summarise(average_price = mean(price)) %>%
  mutate(average_price = round(average_price / 1000, 1))

ggplot_hbar_facet(plot_data, average_price, cut, clarity,
                  facet_ncol = 4,
                  title = "Average diamond price by cut and clarity", 
                  x_title = "Average price ($US thousands)", 
                  y_title = "Cut")

```

4. A `ggplot` coloured and facetted (e.g. `ggplot_hbar_col_facet`)
```{r, message = FALSE, warning = FALSE, fig.height = 5, fig.width = 7}
plot_data <- ggplot2::diamonds %>%
  mutate(cut = stringr::str_to_sentence(cut)) %>%
  group_by(cut, clarity, color) %>%
  summarise(average_price = mean(price)) %>%
  mutate(average_price = round(average_price / 1000, 1))

ggplot_hbar_col_facet(plot_data, average_price, color, clarity, cut,
                      title = "Average diamond price by colour, clarity and cut", 
                      x_title = "Average price ($US thousands)", 
                      y_title = "Colour")

```

These `ggplot` graphs have been designed that users can convert them easily to html interactive objects by wrapping them in `plotly::ggplotly(plot)`. A customised tooltip can be provided using the `text_var` argument in `simplevis` functions with `plotly::ggplotly(plot, tooltip = "text")`. Automated `text` columns can be created using the `mutate_text` function.

```{r, echo = TRUE, eval = FALSE, message = FALSE, warning = FALSE, fig.height = 4, fig.width = 7}
plot_data <- storms %>%
  group_by(year) %>%
  summarise(average_wind = round(mean(wind), 2))

plot <- ggplot_vbar(data = plot_data, 
                    x_var = year, 
                    y_var = average_wind, 
                    title = "Average wind speed of Atlantic storms, 1975\u20132015",
                    x_title = "Year",
                    y_title = "Average maximum sustained wind speed (knots)")

plotly::ggplotly(plot) %>% 
  plotly_camera() 
```

The variable types supported by the different groups of functions are outlined below.

```{r, echo = FALSE}
tibble::tribble(
  ~group, ~x_var, ~y_var, ~col_var, ~facet_var, ~stat,
  "vbar", "numeric, date or categorical", "numeric", "categorical or numeric", "categorical", "identity",
  "hbar", "numeric", "categorical", "categorical or numeric", "categorical", "identity",
  "line", "numeric or date", "numeric", "categorical or numeric", "categorical", "identity",
  "point", "numeric", "numeric", "categorical or numeric", "categorical", "identity",
    "boxplot", "categorical", "numeric", NA, "categorical", "boxplot or identity"
  ) %>% 
  DT::datatable()
```

### simplevis ggplot maps

`simplevis` provides simple feature (`sf`) maps (i.e. maps with point, line or polygon features). 

Spatial-temporal array (i.e. `stars`) maps may be supported in future. 

The following functions are available:

* `ggplot_sf`
* `ggplot_sf_col`
* `ggplot_sf_facet`
* `ggplot_sf_col_facet`

These functions work in the same way as the `ggplot` graph functions, but with the following key differences:

* Data must be provided in the format of an `sf` object. 
* Data must be of `POINT`/`MULTIPOINT`, `LINESTRING`/`MULTILINESTRING`, or `POLYGON`/`MULTIPOLYGON` geometry types
* Data can have any coordinate reference system (CRS), but it must be defined
* No `x_var` and `y_var` variables are required
* There is a borders specification, which allows for a further `sf` object as a borders or administrative boundaries to be added to the map. An example New Zealand borders (`nz`) has been provided with the package. 
* They do _not_ support conversion to interactive objects through `plotly::ggplotly`.

```{r, message = FALSE, warning = FALSE, fig.height = 4, fig.width = 7}
ggplot_sf(example_sf_point, 
          borders = nz, 
          point_size = 0.25,
          title = "Site trends, 2008\u201317",
          title_wrap = 40)
```

```{r, message = FALSE, warning = FALSE, fig.height = 4, fig.width = 7}
pal <- c("#4575B4", "#D3D3D3", "#D73027")

ggplot_sf_col(example_sf_point, trend_category, 
              borders = nz, 
              point_size = 0.25, 
              pal = pal, 
              title = "Site trends, 2008\u201317",
              title_wrap = 40)
```

```{r, message = FALSE, warning = FALSE, fig.height = 4, fig.width = 7}
ggplot_sf_facet(example_sf_point, trend_category, 
                borders = nz, 
                point_size = 0.25,
                title = "Site trends, 2008\u201317")
```

```{r, message = FALSE, warning = FALSE, fig.height = 5, fig.width = 7}
pal <- c("#4575B4", "#D3D3D3", "#D73027")

ggplot_sf_col_facet(example_sf_point, trend_category, trend_category,
                    borders = nz, 
                    point_size = 0.25, 
                    pal = pal,
                    title = "Site trends, 1990\u201317")
```

### simplevis leaflet maps

`simplevis` provides `sf` `leaflet` maps.

These work in the same way as the `ggplot` map functions, but with no borders arguments.

Spatial-temporal array (i.e. `stars`) maps may be supported in future. 

```{r, echo = TRUE, results = 'hide', message = FALSE, warning = FALSE, fig.height = 4, fig.width = 7}
leaflet_sf(data = example_sf_polygon)
```

```{r, echo = TRUE, results = 'hide', message = FALSE, warning = FALSE, fig.height = 4, fig.width = 7}
leaflet_sf_col(example_sf_polygon, density, 
               col_method = "bin", 
               col_cuts = c(0, 10, 50, 100, 150, 200, Inf), 
               col_labels_dp = 0,
               title = "Modelled density, 2013-2017")
```

### shiny apps with simplevis

`simplevis` provides two template `shiny` apps called `template1` and `template2`. Users can access these functions by using the `run_template` functions for the applicable app, and then clicking on the `download_code` button to access a zip file of the code. 

```{r, eval=F}
run_template("template1") # a graph and table
run_template("template2") # a leaflet map, as well as graph and table

```

For a simple app, the basic method to create an app is:

* run `run_template("template1")` or  `run_template("template2")` and download the code to use as a template
* In `get_data.R`, extract, process and save your data into the `data` subfolder, including a zip file for download
* In `make_app_vis.R`, draft your visualisations with dummy character inputs
* In `global.R`, read your data in, and create any vectors required
* In `ui.R`, add a app title
* In `ui.R`. add `radioButtons` and other widgets
* In `server.R`, add code within reactive plot_data and plot components, change any dummy character inputs to shiny user inputs. Add a `isMobile = input$isMobile` specification to any simplevis graphs if you are looking to support mobile users as well as desktop
* In `server.R`, add code for map and table components, as applicable
* In `www/About.Rmd`, update as necessary
* If using google tag-manager, obtain a tag and replace `GTM-XXXXXXX` with it in the `www/js/tag-manager-js` file. 

### Iframing apps

Iframing apps can provide a great experience for users.

Template apps are build to be compatible with one of two approaches to iframing:

* if your website has ability for height responsive iframes, then follow the instructions described in the method developed by <a href="https://www.cultureofinsight.com/post/responsive-iframes-for-shiny-apps" target="_blank">Paul Campbell</a>. 
* if your website does not support responsive iframes, then templates apps have css that supports a iframe of 750px for desktop users. The app developer can then code the iframe height to be bigger if a mobile user is detected. If this is not possible, a hyperlink to the app url can be provided to mobile users. Note if you are trying to support mobile users, it is not recommended to facet graphs.