---
title: "Introduction to `ggplot2`"
author: "Valerio Licursi"
date: "June 26, 2024"
institute: "IBPM-CNR"
format: 
  revealjs:
    footer: ""
    code-copy: true
    preview-links: auto
    chalkboard: 
      boardmarker-width: 5
from: markdown+emoji
execute:
  echo: true
editor: 
  markdown: 
    wrap: sentence
---

```{r setup, message=FALSE, warning=FALSE, include=FALSE}

knitr::opts_chunk$set(
  fig.align = "center",
  cache = TRUE
)

library(tidyverse)
```

### Introduction to ggplot2

<br>

**What is `ggplot2`?**

<br>

-   Part of the `tidyverse`
-   Designed for creating complex plots from data in a data frame
-   Based on the **Grammar of Graphics**: a coherent system for describing and building graphs

------------------------------------------------------------------------

### The Grammar of Graphics

-   Visualisation concept created by Leland Wilkinson (1999)
    -   to define the basic elements of a statistical graphic
-   Adapted for R by **Hadley Wickham** (2009)
    -   consistent and compact syntax to describe statistical graphics
    -   highly modular as it breaks up graphs into semantic components

------------------------------------------------------------------------

### Introduction to ggplot2

<br>

**Why use `ggplot2`?**

<br>

-   High customization
-   Elegant and versatile plots
-   Consistent syntax

------------------------------------------------------------------------

### Basic `ggplot2` Syntax

``` r
ggplot(data = <DATA>, mapping = aes(<MAPPINGS>)) +
  <GEOM_FUNCTION>()
```

-   **data**: The data frame containing the variables
-   **aes**: Aesthetic mappings, describing how variables are mapped to visual properties
-   **geom**: Geometric objects, representing what is actually displayed (e.g., points, lines)

------------------------------------------------------------------------

### Anatomy of a `ggplot2` call

``` r
ggplot(
  data = [dataframe], 
  mapping = aes(
    x = [var_x], y = [var_y], 
    color = [var_for_color], 
    shape = [var_for_shape],
    ...
  )
) +
  geom_[some_geom](
    mapping = aes(
      color = [var_for_geom_color],
      ...
    )
  ) +
  ... # other geometries
  scale_[some_axis]_[some_scale]() +
  facet_[some_facet]([formula]) +
  ... # other options
```

------------------------------------------------------------------------

### Creating a Basic Plot

```{r}
ggplot(data = mtcars, aes(x = wt, y = mpg)) +
  geom_point()
```

-   **ggplot()** initializes the plot
-   **aes()** maps the variables
-   **geom_point()** adds a layer of points to the plot

------------------------------------------------------------------------

### Adding Aesthetics

```{r}
ggplot(data = mtcars, aes(x = wt, y = mpg, color = as.factor(cyl))) +
  geom_point()
```

-   **color**: Differentiates points by cylinder count
-   Aesthetics can also include size, shape, and more

------------------------------------------------------------------------

### Titles and Labels

```{r}
ggplot(data = mtcars, aes(x = wt, y = mpg, color = as.factor(cyl))) +
  geom_point() +
  ggtitle("MPG vs Weight of Cars") +
  xlab("Weight (1000 lbs)") +
  ylab("Miles per Gallon") +
  labs(color = "Cylinders")
```

-   **ggtitle()**: Adds a plot title
-   **xlab()** and **ylab()**: Label the axes
-   **labs()**: Additional labels, such as legends

------------------------------------------------------------------------

### Boxplots and Histograms

#### Boxplot Example:

```{r}
ggplot(data = mtcars, aes(x = as.factor(cyl), y = mpg)) +
  geom_boxplot()
```

---

#### Histogram Example:

```{r}
ggplot(data = mtcars, aes(x = mpg)) +
  geom_histogram(binwidth = 2, fill = "blue", color = "black")
```

-   **geom_boxplot()**: Creates boxplots
-   **geom_histogram()**: Creates histograms with specified bin width

------------------------------------------------------------------------

### Faceting

```{r}
ggplot(data = mtcars, aes(x = wt, y = mpg)) +
  geom_point() +
  facet_wrap(~ cyl)
```

-   **facet_wrap(\~ variable)**: Creates a separate plot for each level of the variable

------------------------------------------------------------------------

### Customizing Themes

``` r
ggplot(data = mtcars, aes(x = wt, y = mpg)) +
  geom_point() +
  theme_minimal()
```

-   **theme_minimal()**: Applies a minimal theme
-   Other themes include **theme_classic()**, **theme_dark()**, etc.

------------------------------------------------------------------------

### Saving Plots

``` r
ggplot(data = mtcars, aes(x = wt, y = mpg)) +
  geom_point()
ggsave("scatter_plot.png")
```

-   **ggsave()**: Saves the last plot to a file
-   Can specify file format (PDF, PNG, ...), dimensions, and more

------------------------------------------------------------------------

## Diamonds

```{r}
set.seed(2024)
diamonds <- sample_n(ggplot2::diamonds, 1000)
diamonds
```

---

```{r}
head(diamonds$cut)
head(diamonds$color)
```

------------------------------------------------------------------------

## Example 1

```{r echo=FALSE, fig.height=5, fig.width=7, warning=FALSE}
ggplot(data = diamonds, aes(x = carat, y = price)) +
  geom_point()
```

::: {style="font-size: 0.5em"}
- Which data are used as an input?
- Are the variables transformed before plotting?
- What geometric objects are used to represent the data?
- What variables are mapped onto which aesthetic attributes?
:::

------------------------------------------------------------------------

```{r fig.height=5, fig.width=7}
ggplot(data = diamonds, aes(x = carat, y = price)) +
  geom_point()
```

------------------------------------------------------------------------

## Altering aesthetics

```{r echo=FALSE, fig.height=5, fig.width=7, warning=FALSE}
ggplot(data = diamonds, aes(x = carat, y = price)) +
  geom_point(alpha = 0.25, color = "blue")
```

::: {style="font-size: 0.75em"}
- How did the plot change?
- Are these changes based on data or are the changes based on stylistic choices for the geometric objects?
:::

------------------------------------------------------------------------

```{r fig.height=5, fig.width=7, warning=FALSE}
ggplot(data = diamonds, aes(x = carat, y = price)) +
  geom_point(alpha = 0.25, color = "blue")
```

------------------------------------------------------------------------

## Example 2

```{r echo=FALSE, fig.height=5, fig.width=7}
ggplot(data = diamonds, aes(x = carat, y = sqrt(price), color = color)) +
  geom_point()
```

::: {style="font-size: 0.5em"}
- Which data are used as an input?
- Are the variables transformed before plotting?
- What geometric objects are used to represent the data?
- What variables are mapped onto which aesthetic attributes?
:::

------------------------------------------------------------------------

```{r, fig.height=5, fig.width=7}
ggplot(data = diamonds, aes(x = carat, y = sqrt(price), color = color)) +
  geom_point()
```

------------------------------------------------------------------------

## Example 3

```{r echo=FALSE, fig.height=5, fig.width=7}
ggplot(data = diamonds, aes(x = carat, y = sqrt(price), color = table)) +
  geom_point()
```

::: {style="font-size: 0.5em"}
- Which data are used as an input?
- Are the variables transformed before plotting?
- What geometric objects are used to represent the data?
- What variables are mapped onto which aesthetic attributes?
:::

------------------------------------------------------------------------

```{r, fig.height=5, fig.width=7}
ggplot(data = diamonds, aes(x = carat, y = sqrt(price), color = table)) +
  geom_point()
```

------------------------------------------------------------------------

## Example 4

```{r echo=FALSE, fig.height=5, fig.width=10}
ggplot(data = diamonds, aes(x = cut, y = price, fill = color)) +
  geom_boxplot() +
  scale_y_log10()
```

::: {style="font-size: 0.5em"}
- Which data are used as an input?
- Are the variables transformed before plotting?
- What geometric objects are used to represent the data?
- What variables are mapped onto which aesthetic attributes?
:::

------------------------------------------------------------------------

```{r fig.height=5, fig.width=10}
ggplot(data = diamonds, aes(x = cut, y = price, fill = color)) +
  geom_boxplot() +
  scale_y_log10()
```

------------------------------------------------------------------------

```{r fig.height=5, fig.width=10}
ggplot(data = diamonds, aes(x = cut, y = log(price,10), fill = color)) +
  geom_boxplot() +
  scale_y_continuous()
```

------------------------------------------------------------------------

## Example 5

```{r echo=FALSE, fig.height=5, fig.width=10}
ggplot(data = diamonds, aes(x = cut, fill=color)) +
  geom_bar(position = "dodge", color = "black") +
  coord_flip() +
  scale_fill_brewer(palette = "Blues")
```

::: {style="font-size: 0.5em"}
- Which data are used as an input?
- Are the variables transformed before plotting?
- What geometric objects are used to represent the data?
- What variables are mapped onto which aesthetic attributes?
- What type of scales are used to map data to aesthetics?
:::

------------------------------------------------------------------------

```{r, fig.height=5, fig.width=10}
ggplot(data = diamonds, aes(x = cut, fill=color)) +
  geom_bar(position = "dodge", color = "black") +
  coord_flip() +
  scale_fill_brewer(palette = "Blues")
```

------------------------------------------------------------------------

## Example 6

```{r echo=FALSE, fig.height=5, fig.width=10}
ggplot(data = ggplot2::diamonds, aes(x = price/carat, fill=color)) +
  geom_density(alpha=0.5) +
  facet_grid(rows = vars(color), cols = vars(cut)) +
  scale_x_sqrt() + 
  labs(x = "Price per carat")
```

::: {style="font-size: 0.55em"}
-   Which data are used as an input?
-   Are the variables transformed before plotting?
-   What geometric objects are used to represent the data?
-   What variables are mapped onto which aesthetic attributes?
-   What type of scales are used to map data to aesthetics?
:::

------------------------------------------------------------------------

```{r fig.height=5, fig.width=10}
ggplot(data = ggplot2::diamonds, aes(x = price/carat, fill=color)) +
  geom_density(alpha=0.5) +
  facet_grid(rows = vars(color), cols = vars(cut)) +
  scale_x_sqrt() + 
  labs(x = "Price per carat")
```

------------------------------------------------------------------------

## `ggplot` objects

```{r cache=TRUE}
g <- ggplot(diamonds, aes(x = carat, y = price)) + geom_point()
class(g)
```

:::: {.columns}
::: {.column width="50%"}
```{r}
g
```
:::

::: {.column width="50%"}
```{r message=FALSE}
g + geom_smooth(se=FALSE)
```
:::
::::

---

## Multi panel Plots

```{r cache=TRUE}
#| code-line-numbers: "1"

library(patchwork)

p1 <- ggplot(diamonds) + geom_point(aes(x = carat, y = price))

p2 <- ggplot(diamonds) + geom_boxplot(aes(x = cut, y = price))

p3 <- ggplot(diamonds) + geom_boxplot(aes(x = color, y = price))

p4 <- ggplot(diamonds) + geom_boxplot(aes(x = clarity, y = price))
```

---

```{r fig.width=10}
p1 + p2 + p3 + p4
```

---

```{r fig.width=10}
p1 + p2 + p3 + p4 + plot_layout(nrow=1)
```

---

```{r fig.width=10}
p1 / (p2 + p3 + p4)
```

---

```{r fig.width=10}
p1 + {
  p2 + {
    p3 + p4 + plot_layout(ncol = 1)
  }
} + plot_layout(ncol = 1)
```

---

```{r fig.width=10}
p1 + p2 + p3 + p4 + plot_annotation(title = "Diamonds data", tag_levels = c("A","1"))
```

# Why do we visualize?

---

## Asncombe's Quartet

```{r}
datasets::anscombe %>% as_tibble()
```

---

## Asncombe's Quartet

Anscombe's quartet comprises four datasets that have __nearly identical__ simple descriptive statistics, yet have very __different distributions__ and appear very different when graphed. 
Each dataset consists of eleven (x, y) points. They were constructed in 1973 by the statistician Francis Anscombe to demonstrate both the importance of graphing data when analyzing it, and the effect of outliers and other influential observations on statistical properties.

::: {style="font-size: 0.55em"}
from: https://en.wikipedia.org/wiki/Anscombe%27s_quartet
:::

---

## Tidy Anscombe

::: {style="font-size: 0.75em"}
```{r}
tidy_anscombe <- datasets::anscombe %>%
  pivot_longer(everything(), names_sep = 1, names_to = c("var", "group")) %>%
  pivot_wider(id_cols = group, names_from = var, 
              values_from = value, values_fn = list(value = list)) %>% 
  unnest(cols = c(x,y))
```
:::

---

### Tidy Anscombe

```{r}
tidy_anscombe %>%
  group_by(group) %>%
  summarize(mean_x = mean(x), mean_y = mean(y), sd_x = sd(x), sd_y = sd(y), cor = cor(x,y))
```

---

### Tidy Anscombe


```{r fig.width=7}
ggplot(tidy_anscombe, aes(x = x, y = y, color = as.factor(group))) +
  geom_point(size=2) +
  facet_wrap(vars(group)) +
  geom_smooth(method="lm", se=FALSE, fullrange=TRUE) +
  guides(color=FALSE)
```

---

## DatasauRus

:::: {.columns}
::: {.column width="50%"}
```{r}
datasauRus::datasaurus_dozen
```


:::
::: {.column width="50%"}

```{r}
datasauRus::datasaurus_dozen %>%
  group_by(dataset) %>%
  summarize(mean_x = mean(x), mean_y = mean(y), 
            sd_x = sd(x), sd_y = sd(y), 
            cor = cor(x,y))
```
:::
::::

---

```{r}
ggplot(datasauRus::datasaurus_dozen, aes(x = x, y = y, color = dataset)) +
  geom_point() +
  facet_wrap(vars(dataset)) +
  guides(color=FALSE)
```

---

## DatasauRus

The *Datasaurus* dozen comprises thirteen data sets that have nearly identical simple descriptive statistics to two decimal places, yet have very different distributions and appear very different when graphed.
It was inspired by the smaller Anscombe's quartet that was created in 1973. 

::: {style="font-size: 0.55em"}
from: https://en.wikipedia.org/wiki/Datasaurus_dozen
:::

------------------------------------------------------------------------

### Resources

-   [**ggplot2 documentation**](https://ggplot2.tidyverse.org/)
-   [**R Graphics Cookbook by Winston Chang**](http://www.cookbook-r.com/Graphs/)
-   [**R for Data Science by Hadley Wickham and Garrett Grolemund**](https://r4ds.had.co.nz/)
