---
title: "Visualization 2<br>Using ggplot"
author: "Keith VanderLinden<br>Calvin University"
output:
  xaringan::moon_reader:
    nature:
      titleSlideClass: ["left", "top"]
      highlightLines: true
      ratio: "16:9"
---

# Data Visualization using ggplot

.pull-left[
ggplot2 is Tidyverse&rsquo;s data visualization package. It supports EDA by allowing users to specify plots in a declarative manner and to build them iteratively.


]
.pull-right[
![ggplot logo](https://cs.calvin.edu/courses/info/601/resources/images/tidyverse-ggplot2.png)
]

???
Being part of Tidyverse means that ggplot will stream with tibbles.

---
# Grammar of Graphics

ggplot2 implements data visualizations using a layered *grammar of graphics*.

.pull-left[
![gg](https://cs.calvin.edu/courses/info/601/resources/images/grammar-of-graphics.png)

See: *The Grammar of Graphics*, L. Wilkinson, https://www.springer.com/in/book/9780387245447

]

.pull-right[
```{r eval=FALSE}
<DATA> %>%          #<<
  ggplot() +        #<<
  aes( <MAPPINGS> ) #<<
  <GEOM_FUNCTION>(  #<<
    stat = <STAT> , 
    position = <POSITION> 
    ) +
  <COORDINATE_FUNCTION> +
  <FACET_FUNCTION> +
  <SCALE_FUNCTION> +
  <THEME_FUNCTION>
```

<br><br>
See: *A Layered Grammar of Graphics*, H. Wickam, http://vita.had.co.nz/papers/layered-grammar.pdf

]

???
Notes:
- The data, geom, mappings lines are required; the rest are optional.
- Distinguish `%>%` (data pipe - newer) vs `+` (add ggplot layer - older).
- Be careful of the three views of graphics here.
  - *Yau's taxonomy* (MDSR 2), covered in unit 2, is used only to analyze graphs.
  - *Wilkinson's Grammar of Graphics*, which inspired Wickam's ggplot, is mentioned here only as background and to introduce the idea of layering graphics.
  - *Wickham's `ggplot`* (R4DS 3, MDSR 3), which is what data scientists actually use.

---
# ggplot Coding Example

```{r packages, echo = FALSE, message = FALSE, warning = FALSE}
library(tidyverse)
```

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

penguins
```

.footnote[Based on [Data Science in a Box](https://datasciencebox.org)]

---

.pull-left[
```{r penguins-0, fig.show = "hide", warning = FALSE}
penguins %>%  #<<
  ggplot()    #<<
```
]
.pull-right[
```{r ref.label="penguins-0", echo = FALSE, warning = FALSE, out.width = "100%", fig.width = 8}
```
]
.midi[
> **Start with the `penguins` data frame and initialize the plot.**
]

---

.pull-left[
```{r penguins-1, fig.show = "hide", warning = FALSE}
penguins %>%
  ggplot() +
  aes(x = bill_depth_mm) #<<
```
]
.pull-right[
```{r ref.label = "penguins-1", echo = FALSE, warning = FALSE, out.width = "100%", fig.width = 8}
```
]
.midi[
> Start with the `penguins` data frame
> and initialize the plot.
> **Map bill depth to the x-axis**
]

---

.pull-left[
```{r penguins-2, fig.show = "hide", warning = FALSE}
penguins %>%
  ggplot() +
  aes(x = bill_depth_mm,
      y = bill_length_mm) #<<
```
]
.pull-right[
```{r ref.label = "penguins-2", echo = FALSE, warning = FALSE, out.width = "100%", fig.width = 8}
```
]
.midi[
> Start with the `penguins` data frame
> and initialize the plot.
> Map bill depth to the x-axis
> **and map bill length to the y-axis.**
]

---

.pull-left[
```{r penguins-3, fig.show = "hide", warning = FALSE}
penguins %>%
  ggplot() + 
  aes(x = bill_depth_mm,
      y = bill_length_mm) +
  geom_point() #<<
```
]
.pull-right[
```{r ref.label = "penguins-3", echo = FALSE, warning = FALSE, out.width = "100%", fig.width = 8}
```
]
.midi[
> Start with the `penguins` data frame
> and initialize the plot.
> Map bill depth to the x-axis
> and map bill length to the y-axis. 
> **Represent each observation with a point**
]

---

.pull-left[
```{r penguins-4, fig.show = "hide", warning = FALSE}
penguins %>%
  ggplot() +
  aes(x = bill_depth_mm,
      y = bill_length_mm,
      color = species) + #<<
  geom_point()
```
]
.pull-right[
```{r ref.label = "penguins-4", echo = FALSE, warning = FALSE, out.width = "100%", fig.width = 8}
```
]
.midi[
> Start with the `penguins` data frame
> and initialize the plot.
> Map bill depth to the x-axis
> and map bill length to the y-axis. 
> Represent each observation with a point
> **and map species to the color of each point.**
]

---

.pull-left[
```{r penguins-5, fig.show = "hide", warning = FALSE}
penguins %>%
  ggplot() +
  aes(x = bill_depth_mm,
      y = bill_length_mm,
      color = species) +
  geom_point() +
  labs(                                      #<<
    title = "Penguin bill depth and length"  #<<
    )                                        #<<
```
]
.pull-right[
```{r ref.label = "penguins-5", echo = FALSE, warning = FALSE, out.width = "100%", fig.width = 8}
```
]
.midi[
> Start with the `penguins` data frame
> and initialize the plot.
> Map bill depth to the x-axis
> and map bill length to the y-axis. 
> Represent each observation with a point
> and map species to the color of each point.
> **Title the plot "Penguin bill depth and length"**
]

---

.pull-left[
```{r penguins-6, fig.show = "hide", warning = FALSE}
penguins %>%
  ggplot() +
  aes(x = bill_depth_mm,
      y = bill_length_mm,
      color = species) +
  geom_point() +
  labs(
    title = "Penguin bill depth and length",
    subtitle = "Adelie, Chinstrap, Gentoo" #<<
    )
```
]
.pull-right[
```{r ref.label = "penguins-6", echo = FALSE, warning = FALSE, out.width = "100%", fig.width = 8}
```
]
.midi[
> Start with the `penguins` data frame
> and initialize the plot.
> Map bill depth to the x-axis
> and map bill length to the y-axis. 
> Represent each observation with a point
> and map species to the color of each point.
> Title the plot "Penguin bill depth and length", 
> **add the subtitle "Adelie, Chinstrap, Gentoo"**
]

---

.pull-left[
```{r penguins-7, fig.show = "hide", warning = FALSE}
penguins %>%
  ggplot() +
  aes(x = bill_depth_mm,
      y = bill_length_mm,
      color = species) +
  geom_point() +
  labs(
    title = "Penguin bill depth and length",
    subtitle = "Adelie, Chinstrap, Gentoo",
    x = "Bill depth (mm)", #<<
    y = "Bill length (mm)" #<<
    )
```
]
.pull-right[
```{r ref.label = "penguins-7", echo = FALSE, warning = FALSE, out.width = "100%", fig.width = 8}
```
]
.midi[
> Start with the `penguins` data frame
> and initialize the plot.
> Map bill depth to the x-axis
> and map bill length to the y-axis. 
> Represent each observation with a point
> and map species to the color of each point.
> Title the plot "Penguin bill depth and length", 
> add the subtitle "Adelie, Chinstrap, Gentoo", 
> **label the x and y axes as "Bill depth (mm)" and "Bill length (mm)", respectively**
]

---

.pull-left[
```{r penguins-8, fig.show = "hide", warning = FALSE}
penguins %>%
  ggplot() +
  aes(x = bill_depth_mm,
      y = bill_length_mm,
      color = species) +
  geom_point() +
  labs(
    title = "Penguin bill depth and length",
    subtitle = "Adelie, Chinstrap, Gentoo",
    x = "Bill depth (mm)", 
    y = "Bill length (mm)",
    color = "Species", #<<
    )
```
]
.pull-right[
```{r ref.label = "penguins-8", echo = FALSE, warning = FALSE, out.width = "100%", fig.width = 8}
```
]
.midi[
> Start with the `penguins` data frame
> and initialize the plot.
> Map bill depth to the x-axis
> and map bill length to the y-axis. 
> Represent each observation with a point
> and map species to the color of each point.
> Title the plot "Penguin bill depth and length", 
> add the subtitle "Adelie, Chinstrap, Gentoo", 
> label the x and y axes as "Bill depth (mm)" and "Bill length (mm)", respectively,
> **label the legend "Species"**
]

---

.pull-left[
```{r penguins-9, fig.show = "hide", warning = FALSE}
penguins %>%
  ggplot() +
  aes(x = bill_depth_mm,
      y = bill_length_mm,
      color = species) +
  geom_point() +
  labs(
    title = "Penguin bill depth and length",
    subtitle = "Adelie, Chinstrap, Gentoo",
    x = "Bill depth (mm)", 
    y = "Bill length (mm)",
    color = "Species",
    caption = "Source: Palmer Station LTER" #<<
    )
```
]
.pull-right[
```{r ref.label = "penguins-9", echo = FALSE, warning = FALSE, out.width = "100%", fig.width = 8}
```
]
.midi[
> Start with the `penguins` data frame
> and initialize the plot.
> Map bill depth to the x-axis
> and map bill length to the y-axis. 
> Represent each observation with a point
> and map species to the color of each point.
> Title the plot "Penguin bill depth and length", 
> add the subtitle "Adelie, Chinstrap, Gentoo", 
> label the x and y axes as "Bill depth (mm)" and "Bill length (mm)", respectively,
> label the legend "Species", 
> **and add a caption for the data source.**
]

---

.pull-left[
```{r penguins-10, fig.show = "hide", warning = FALSE}
penguins %>%
  ggplot() +
  aes(x = bill_depth_mm,
      y = bill_length_mm,
      color = species) +
  geom_point() +
  labs(
    title = "Penguin bill depth and length",
    subtitle = "Adelie, Chinstrap, Gentoo",
    x = "Bill depth (mm)", 
    y = "Bill length (mm)",
    color = "Species",
    caption = "Source: Palmer Station LTER"
    ) +
  scale_color_viridis_d() #<<
```
]
.pull-right[
```{r ref.label = "penguins-10", echo = FALSE, warning = FALSE, out.width = "100%", fig.width = 8}
```
]
.midi[
> Start with the `penguins` data frame
> and initialize the plot.
> Map bill depth to the x-axis
> and map bill length to the y-axis. 
> Represent each observation with a point
> and map species to the color of each point.
> Title the plot "Penguin bill depth and length", 
> add the subtitle "Adelie, Chinstrap, Gentoo", 
> label the x and y axes as "Bill depth (mm)" and "Bill length (mm)", respectively,
> label the legend "Species", 
> and add a caption for the data source.
> **Finally, use a discrete color scale that is designed to be perceived by viewers with common forms of color blindness.**
]

---
# Aesthetic Options

.pull-left[
Some aesthetics options are mapped to specific variables.
```{r penguins-aesthetics, fig.show = "hide", warning = FALSE}
penguins %>%
  ggplot() +
  aes(x = bill_depth_mm,
      y = bill_length_mm,
      color = species,             #<<
      shape = species,             #<<
      size = body_mass_g,          #<<
      alpha = flipper_length_mm) + #<<
  geom_point() +
  scale_color_viridis_d()
```
]
.pull-right[
```{r ref.label = "penguins-aesthetics", echo = FALSE, warning = FALSE, out.width = "100%", fig.width = 8}
```

]

???
Point out the 4 aesthetics in the resulting plot. One variable (`species`) has two aesthetic forms.

Distinguish between:
- *mapping*: `color = species` is currently in `aes()` and, thus, is based on the value of the `species` variable.
- *setting*: Setting `color="blue"` in geom_point() sets every geom to blue.

---
# Geometric Options

.pull-left[
Some aesthetics options are mapped to specific variables.
```{r penguins-geometry, fig.show = "hide", warning = FALSE}
penguins %>%
  ggplot() +
  aes(x = bill_depth_mm,
      y = bill_length_mm,
      color = species,
      linetype = species) +            #<<
  geom_point() +
  geom_smooth() +                      #<<
  scale_color_viridis_d()
```
]
.pull-right[
```{r ref.label = "penguins-geometry", echo = FALSE, message = FALSE, warning = FALSE, out.width = "100%", fig.width = 8}
```

]

???
Notes:
- This plot has two geoms; only one is needed.
- Not all aesthetic options work with all geometries, e.g., lines have `linetype`, not `shape`. 

---
# Faceting (1D)

.pull-left[
Faceting creates separate, smaller plots that display subsets of the data.
```{r penguins-facets1, fig.show = "hide", warning = FALSE}
penguins %>%
  ggplot() +
  aes(x = bill_depth_mm, 
      y = bill_length_mm) + 
  geom_point() +
  facet_wrap(~ species) #<<
```
]
.pull-right[
```{r ref.label = "penguins-facets1", echo = FALSE, warning = FALSE, out.width = "100%", fig.width = 8, fig.height = 4}
```
]

???
This is called *small multiples* in N. Yao's taxonomy (MDSR 2.2.1). 

---
# Faceting (2D)

.pull-left[
This is useful for exploring conditional relationships and large datasets.
```{r penguins-facets2, fig.show = "hide", warning = FALSE}
penguins %>%
  ggplot() +
  aes(x = bill_depth_mm, 
      y = bill_length_mm) + 
  geom_point() +
  facet_grid(sex ~ species) #<<
```
]
.pull-right[
```{r ref.label = "penguins-facets2", echo = FALSE, warning = FALSE, out.width = "100%", fig.width = 8}
```
]

???

See datascience Box <https://datasciencebox.org/exploring-data.html> for more faceting options.
