---
title: "Using warwickplots with ggplot2"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Using warwickplots with ggplot2}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

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

```{r setup}
library(warwickplots)
```


```{r setup2, message = FALSE}
library(ggplot2)
library(palmerpenguins)
library(dplyr)
library(ggtext)
```

Note: In the version of this vignette available within R, the plots do not look good. Please read the vignette [online](https://warwick-stats-resources.github.io/warwickplots/articles/ggplot2.html) instead.

Below are several example plots, made with [ggplot2](https://ggplot2.tidyverse.org) demonstrating the usage of the various palettes in `warwick_palettes` and `theme_warwick()`.

First, let's define a starting plot:

```{r}
p <- ggplot(penguins, aes(flipper_length_mm, body_mass_g, group = species)) +
  geom_point(aes(colour = species, shape = species), alpha = 0.8, size = 2) +
  labs(title = "Penguin Size, Palmer Station LTER",
       caption = "Visualization: Ella Kaye",
       x = "flipper length (mm)",
       y = "body mass (g)") +
  theme_warwick()
  
p
```

## Using colour and fill scales

#### Discrete

Use `scale_colour_palette_d()` and `scale_fill_palette_d()` for discrete scales:

```{r}
p +
  scale_colour_palette_d(warwick_palettes$primary) 
```

```{r}
p +
  scale_colour_palette_d(warwick_palettes$primary[c(1, 3, 5)]) 
```

```{r}
mpg |> 
  filter(class != "2seater") |> 
  ggplot(aes(y = fl, fill = class)) +
    geom_bar() +
    scale_fill_palette_d(warwick_palettes$primary) +
    theme_warwick()
```

#### Sequential

```{r}
ggplot(diamonds[sample(nrow(diamonds), 1000), ], aes(carat, price)) +
  geom_point(aes(colour = clarity)) +
  scale_colour_palette_d(warwick_palettes$aubergine)
```

Use `scale_colour_palette_c()` and `scale_fill_palette_c()` for continuous scales and `scale_colour_palette_b()` and `scale_fill_palette_b()` for binned scales:

```{r}
eruptions <- ggplot(faithfuld, aes(waiting, eruptions, fill = density)) +
  geom_tile()

eruptions + 
  scale_fill_palette_c(warwick_palettes$ruby)

eruptions + 
  scale_fill_palette_b(warwick_palettes$teal)
```

#### Divergent

To demonstrate the divergent palettes, let's first generate some synthetic data to plot on a map:

```{r}
library(maps)
# Get US state boundaries
us_states <- map_data("state")

# Generate synthetic data
set.seed(123)
states <- unique(us_states$region)
n <- length(states)
data <- data.frame(
  region = states,
  value = rnorm(n, mean = .5)
)

# Merge the synthetic data with the map data
us_states <- us_states |> 
  left_join(data, by = "region")

# Create the plot (without colour)
map_p <- ggplot(us_states, aes(x = long, y = lat, group = group, fill = value)) +
  geom_polygon(color = "white") +
  labs(title = "Divergent Data by US State") +
  theme_warwick()
```

We can now add a divergent colour palette:

```{r}
map_p + 
  scale_fill_palette_c(warwick_palettes$aubergine_ruby)
```

By default, the fill scale’s mid-point is the mean of the groups. If we want it to be zero, we can use the rescaler argument in `ggplot2::continuous_scale()`, which accepts a function used to scale the input values to the range [0, 1], to scale the fill values to have a mid-point of zero. For scaling the mid-point use `scales::rescale_mid()`:

```{r}
map_p +
  scale_fill_palette_c(warwick_palettes$aubergine_ruby,
                       rescaler = ~ scales::rescale_mid(.x, mid = 0))
```

See the [using palettes with ggplot2](https://mccarthy-m-g.github.io/palettes/articles/ggplot2.html) vignette in the palettes package for more details.

## More on `theme_warwick()`

Let's return to some earlier examples to see how to get the most out of `theme_warwick()`.

`theme_warwick()` makes use of `ggtext::element_textbox_simple()` for the plot title and subtitle. This allows us to make use of markdown and CSS styles in the text, and also enables text-wrapping:

```{r}
new_p <- p +
  labs(subtitle = "Flipper length and body mass for **<span style = 'color:#3C1053;'>Adelie</span>**, **<span style = 'color:#6DCDB8;'>Chinstrap</span>** and **<span style = 'color:#CB333B;'>Gentoo</span>** Penguins. This is based on data made available in the **palmerpenguins** R package.") +
  scale_color_palette_d(warwick_palettes$primary)

new_p
```

We can now use `theme()` to make further adjustments to the appearance of the plot. Now that we have colour for the different species in the subtitle, we no longer need the legend. Let's also alter some of the text. Note that because the title is set in `theme_warwick()` as a `ggtext::element_textbox_simple()`, you need to use that in the subsequent call to theme, whereas to change the appearance of other text, e.g. the caption, you just need the standard `ggplot2::element_text()`:

```{r}
new_p + 
  theme(legend.position = "none",
        plot.title = ggtext::element_textbox_simple(size = rel(1.6)),
        plot.caption = element_text(colour = "#CB333B"))
```

Note that the title and subtitle now have less space between them. This is because, in `theme_warwick()` the spacing is defined in the definition of `plot.title` and that has now been overwritten, so we need to put it back. We can inspect the source code by calling `theme_warwick` in the console (without the parentheses), or with `View(theme_warwick)`. We can then see the whole definition of `plot.title` and put the definition of `margin` back in (the text colour can stay as is):

```{r}
new_p + 
  theme(legend.position = "none",
        plot.title = element_textbox_simple(size = rel(1.6),
                                            margin = margin(12, 0, 6, 0)),
        plot.caption = element_text(colour = "#CB333B"))
```

## Typography and setting up custom fonts

The University of Warwick's [typography brand guidance](https://warwick.ac.uk/about/brand/brand-guidelines/typography/) is to use the font Lato for all online text and the font Avenir Next for all print material. `theme_warwick()` has a `use` argument, that can be one of `"online"` or `"print"` (defaults to `"online"`), which will ensure the appropriate font for the use, *if* your system is set up for it, i.e. you have the fonts installed and the packages to render them in a plot. For details on how to ensure that your system is properly set up for this, see the [get started with warwickplots](https://warwick-stats-resources.github.io/warwickplots/articles/warwickplots.html#typography-and-setting-up-custom-fonts) vignette.
