---
title: "Simplevis"
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.

The aim is of simplevis is to make the majority of visualisations easier, while supporting users to move between ggplot2 and simplevis as needed. 

simplevis makes things easier by:

* minimising visualisation types available to vbar, hbar, point, line, boxplot or sf 
* minimising aesthetics available to x, y, colour and facetting
* using a simpler method for colouring
* using consistent prefixes and the Rstudio auto-complete function
* using ggplot2 based terminology for leaflet visualisation.

The package also supports making mobile-friendly visualisation for mobile devices.

### Overview

`simplevis` provides the following families of ggplot2 visualisation:

Graph:

* horizontal bar (`ggplot_hbar`)
* vertical bar (`ggplot_vbar`)
* line plot (`ggplot_line`)
* scatter graph (`ggplot_point`)
* boxplot (`ggplot_boxplot`)

Map:

* sf (`ggplot_sf`)

Each visualisation family has a family of generally 4 functions.

The function name specifies whether or not a ggplot is to be coloured by a variable, facetted by a variable, or neither or both of these. Colouring by a variable means that different values of a selected variable are to have different colours. Facetting means different values of a selected variable are to have there own mini-plot, and these are to be placed alongside each other.

Each ggplot2 wrapper family follows the structure as below:

* `ggplot_hbar()`: a horizontal bar graph.
* `ggplot_hbar_col()`: a horizontal bar graph that is coloured by a variable.
* `ggplot_hbar_facet()`: a facetted horizontal bar graph.
* `ggplot_hbar_col_facet()`a facetted horizontal bar graph that is coloured by a variable.

For different types of graph, just replace `ggplot_hbar` with `ggplot_line`, `ggplot_point`, `ggplot_vbar`, `ggplot_boxplot` or `ggplot_sf`. 

In general, required arguments (i.e. specifications) to functions are:

* `data` 
* `x_var` (not required for `sf`)
* `y_var` (not required for `sf`) 

If you are using a `_col` or `_col_facet` function:

* `col_var`

If you are using a `_facet` or `_col_facet` function:

* `facet_var`

It is always recommended to add a `title`, `x_title` and `y_title` too. 

### Plots <i>not</i> coloured by a variable.

Identify the function that you need, then provide the `data`, an `x_var` and a `y_var` (unless of the `ggplot_sf` family).

```{r, message = FALSE, warning = FALSE, fig.height = 3, fig.width = 6}
plot_data <- ggplot2::diamonds %>% 
  slice_sample(prop = 0.05) %>% 
  tibble::as_tibble()

plot_data

ggplot_point(plot_data, carat, price)
```

```{r, message = FALSE, warning = FALSE, fig.height = 3, fig.width = 6}
plot_data <- ggplot2::diamonds %>%
  group_by(cut) %>%
  summarise(average_price = mean(price)) %>%
  mutate(average_price = average_price / 1000) %>%  
  mutate(cut = stringr::str_to_sentence(cut)) %>% 
  tibble::as_tibble()

plot_data

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

```{r, message = FALSE, warning = FALSE, fig.height = 3, fig.width = 6}
plot_data <- storms %>%
  group_by(year) %>%
  summarise(average_wind = mean(wind)) %>% 
  tibble::as_tibble()

plot_data

ggplot_vbar(plot_data, 
            x_var = year, 
            y_var = average_wind)
```

```{r, message = FALSE, warning = FALSE, fig.height = 3, fig.width = 6}
plot_data <- storms %>%
  group_by(year) %>%
  summarise(wind = mean(wind)) %>% 
  tibble::as_tibble()

plot_data 

ggplot_line(plot_data, 
            x_var = year, 
            y_var = wind)
```

Note the `ggplot_boxplot` functions transform the data to boxplot statistics by default. 

```{r, message = FALSE, warning = FALSE, fig.height = 3, fig.width = 6}
plot_data <- iris %>%
  mutate(Species = stringr::str_to_sentence(Species)) %>% 
  tibble::as_tibble()

plot_data

ggplot_boxplot(plot_data, 
               x_var = Species, 
               y_var = Petal.Length)
```

### Plots coloured by a variable

To colour by a variable, use a `_col` function (e.g. `ggplot_hbar_col`). Add a `col_var` variable in addition.

```{r, message = FALSE, warning = FALSE, fig.height = 3.5, fig.width = 6}
plot_data <- ggplot2::diamonds %>%
  group_by(cut, clarity) %>%
  summarise(average_price = mean(price)) %>% 
  mutate(average_price = average_price / 1000) %>% 
  mutate(cut = stringr::str_to_sentence(cut)) %>% 
  tibble::as_tibble()

plot_data

ggplot_hbar_col(plot_data, 
                x_var = average_price, 
                y_var = cut, 
                col_var = clarity)
```

### Plots facetted by a variable

To facet by a variable, use a `_facet` function.

```{r, message = FALSE, warning = FALSE, fig.height = 5, 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 = average_price / 1000) %>% 
  tibble::as_tibble()

plot_data

ggplot_hbar_facet(plot_data, 
                  x_var = average_price, 
                  y_var = cut, 
                  facet_var = clarity)
```

### Plots coloured by a variable and facetted by a variable

facet by a variable, use a `_col_facet` function.

```{r, message = FALSE, warning = FALSE, fig.height = 4.5, fig.width = 6}
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, 
                      x_var = average_price, 
                      y_var = color, 
                      col_var = clarity, 
                      facet_var = cut)
```

### `sf` ggplot maps

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

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

* Data must be an `sf` object 
* Data must be of `POINT`/`MULTIPOINT`, `LINESTRING`/`MULTILINESTRING`, or `POLYGON`/`MULTIPOLYGON` geometry type
* Data must have a coordinate reference system (CRS) defined
* No `x_var` and `y_var` variables are required
* Borders can added to maps by providing an `sf` object to the `borders` argument. 

```{r, message = FALSE, warning = FALSE, fig.height = 3, fig.width = 7}
example_sf_point

ggplot_sf(example_sf_point, 
          size_point = 0.25)
```

```{r, message = FALSE, warning = FALSE, fig.height = 3, fig.width = 7}
nz

ggplot_sf(example_sf_point, 
          borders = nz, 
          size_point = 0.25)
```

```{r, message = FALSE, warning = FALSE, fig.height = 3, fig.width = 7}
example_sf_polygon

ggplot_sf_col(example_sf_polygon, 
              col_var = density, 
              borders = nz)
```

```{r, message = FALSE, warning = FALSE, fig.height = 3, fig.width = 7}
ggplot_sf_facet(example_sf_point, 
                facet_var = trend_category, 
                borders = nz, 
                size_point = 0.5)
```

```{r, message = FALSE, warning = FALSE, fig.height = 3, fig.width = 7}
ggplot_sf_col_facet(example_sf_point, 
                    col_var = trend_category, 
                    facet_var = trend_category,
                    borders = nz, 
                    size_point = 0.5, 
                    pal = c("#4575B4", "#D3D3D3", "#D73027"),
                    title = "Site trends, 1990\u201317")
```

#### ggplot supported variable classes

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

A stat of `identity` refers to the value being plotted as it is. A stat of `boxplot` refers to boxplot statistics being calculated from the data, and these plotted.

```{r, message = FALSE, warning = FALSE, fig.width = 7}
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", "categorical", "categorical", "boxplot or identity",
  "sf", NA, NA, "categorical or numeric", "categorical", "identity",
  ) %>% 
  DT::datatable()
```

### ggplotly interactive html graphs and maps

All ggplot objects can be converted into interactive html objects using ggplotly. Simply wrap the plot object in `plotly::ggplotly` as follows:

```{r, eval = FALSE}
plot <- ggplot_point(iris, Sepal.Width, Sepal.Length)

plotly::ggplotly(plot)
```

For further information on how to use `ggplotly` with `simplevis`, see the [ggplotly article](https://statisticsnz.github.io/simplevis/articles/ggplotly.html) 

### `sf` leaflet html interactive maps 

`simplevis` also provides wrapper functions for `sf` leaflet html interactive maps.

These differ from `ggplotly` interactive plots in that they provide basemaps and zoom functionality. However, they do not support facetting. 

A `leaflet_sf` and `leaflet_sf_col` function are provided. 

They work in essentially the same way as the ggplot2 non-facetted `sf` functions. Arguments have been aligned with simplevis ggplot wrapping functions (e.g. size_point = radius, line_size = weight, alpha = fillOpacity).

```{r, message = FALSE, warning = FALSE, fig.height = 4, fig.width = 7}
leaflet_sf_col(example_sf_point, 
               col_var = trend_category, 
               basemap = "light",
               pal = c("#0D94A3", "#C4C4C7", "#AE4E51"), 
               title = "Monitored trends, 2008\u201317")
```

For further information on how to create leaflet html maps, see the [leaflet article](https://statisticsnz.github.io/simplevis/articles/leaflet.html) 

### Adding layers

Because both of the ggplot and leaflet wrapper functions produce ggplot and leaflet objects, you can add layers in the same way that you would normally to these objects. Be careful to use `+` to add layers to ggplot objects and `%>%` to add to leaflet objects. Data is inherited from the simplevis, but aesthetics are not.

```{r, message = FALSE, warning = FALSE, fig.height = 4, fig.width = 7}
ggplot_point(iris, Sepal.Width, Sepal.Length) +
  ggplot2::geom_smooth(ggplot2::aes(Sepal.Width, Sepal.Length), col = viridis::viridis(4)[2])
```

### Colour 

To change the colours, add a `pal` argument with a vector of hex strings.

```{r, message = FALSE, warning = FALSE, fig.height = 4, fig.width = 7}
ggplot_point(iris, Sepal.Width, Sepal.Length, pal = "#e7298a")
```

```{r, message = FALSE, warning = FALSE, fig.height = 4, fig.width = 7}
ggplot_point_col(iris, Sepal.Width, Sepal.Length, Species, 
                 pal = c("#1B9E77", "#D95F02", "#7570B3"))

```

Colouring works slightly differently in simplevis to ggplot2. For further information, see the [colour article](https://statisticsnz.github.io/simplevis/articles/colour.html). 

### Working with scales

Working with scales can be one of the most challenging aspects of creating a nice visualisation. 'simplevis` uses the power of consistent prefixes and the Rstudio auto-complete to make this easier for users.

For further information, see the [scales article](https://statisticsnz.github.io/simplevis/articles/scales.html).

### Shiny apps for mobile devices 

`simplevis` provides simple methods for supporting visualisation on apps for mobile device users. 

For further information, see the [shiny article](https://statisticsnz.github.io/simplevis/articles/shiny.html).