```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
# handy package manager that installs and loads packages used in this document
if (!("pacman" %in% installed.packages()[,"Package"])) { install.packages("pacman") } 
pacman::p_load(tidyverse, psych, GGally, Rmisc, interactions) # install (if needed) and load packages
```

# Goals of this markdown
This markdown is designed to provide an introduction to data visualization in R. 
Primarily it will cover ggplot2; although a few advanced options are covered here or available in supplementary materials. 
Questions about code can be directed to Alicia Vallorani (auv27 at psu.edu).

## What is ggplot()?
The ggplot() function sets the foundation for building any kind of plot. 
We need to pass ggplot() two main pieces of information: the name of the dataset and the names of the columns in the dataset that we want to plot.

## psych::sat.act dataset
Here, we can see that there's one column per variable and one row per subject. 
This is how we want the data to be set up for plotting in ggplot(). 
This way, we can easily specify the variables we are interested in, and we know that we have a unique value for each subject. Here's an example with the age and ACT variables.

```{r}
# Load data and convert sex and education to factors
source(paste0(params$path_2_scripts, "load_sat_act.R"))

# Print the first five rows in the dataset
head(sat.act, n=5)

# Examine the structure of the dataset
str(sat.act)
```

# Examine univariate distributions - histograms
First, let's examine the distributions of the variables included in the dataset. We can build histograms that look at a single variable or multiple variables simultaneously.

```{r}
# Looking at a histogram for a single variable
ggplot(sat.act, aes(ACT)) +
  geom_histogram(bins = 20) # you can change the bin value to best fit your data

# Looking at histograms for all variables ggplot option
ggplot(sat.act %>% dplyr::select(-sex, -education) %>% # removing dichotomous variables
         gather(), aes(value)) + # grouping for visualization
    geom_histogram(bins = 20) + 
    facet_wrap(~key, scales = "free_x") # free_x allows for differing x-axes 

# 13 rows containing non-finite values = NA values in SATQ
# warnings =/= errors; your code will still run if you get a warning, it just
# lets you know that there may be an issue that you want to consider
```

# Examining zero-order relations - scatterplots
This section walks through how to make a simple scatterplot between two variables. 
Additionally, you can add a fit line and look at how scatterplots may vary across groups.

```{r}
# Simple descriptive scatter plot
ggplot(sat.act, aes(age, ACT)) +
  # geom_ allows you to select the type of object you would like to comprise the graph
  geom_point() + 
  # You can add axis labels and titles
  ylab("Score") + 
  xlab("Age") +
  ggtitle("ACT scores by age") +
  # You can set different themes to alter the general appearance of your graphs (more description in the aesthetics section)
  theme_classic()
```

We can also add more information, like how education factors into the distribution of scores.

```{r}
# Descriptive scatterplot with additional element
scatter <- ggplot(sat.act, aes(age, ACT, color=education)) +
  geom_point() +
  ylab("Score") +
  xlab("Age") +
  labs(color="Education level") +
  ggtitle("ACT scores by age and education level") +
  theme_classic()

# If you have saved your graph into an object, as above, you can call the object to view
scatter
```

Saving your graph to an object allows you to easily add elements. For example, we can add a regression line.  

```{r}
scatter <- scatter + geom_smooth(method="lm", se=FALSE, color="gray50")
scatter
```

In addition to considering bivariate relations two variables at a time (like above), the package GGally contains ggpairs() which allows us to visualize multiple relations simultaneously.

```{r}
ggpairs(sat.act %>% na.omit(), progress=FALSE, 
        lower = list(combo = wrap("facethist", bins=6)))
```

Additional advanced suggestions for scatterplots can be found in the [supplemental materials](https://psu-psychology.github.io/r-bootcamp-2019/talks/data_visualization_supp.html#scatterplots).

# Examining group differences - bar graphs

This section walks through a basic bar graph. If you don't specify a value for the y axis, it'll create counts for you.

```{r}
# Bar graph with counts
ggplot(sat.act, aes(education)) +
  geom_bar() +
  ylab("Number of subjects") +
  xlab("Education level") +
  ggtitle("Count of subjects at each education level") +
  theme_classic()
```

If you want to perform a different summary calculation than a count, you can include the column of data you want and the kind of calculation.

```{r}
# Bar graph with means
ggplot(sat.act, aes(education, ACT)) +
  geom_bar(stat="summary", fun.y="mean") +
  ylab("Average score") +
  xlab("Education level") +
  ggtitle("Average ACT scores at each education level") +
  theme_classic()
```

We can also include error bars using the summarySE() function from the Rmisc package.

```{r}
# Summary data for error bars
sat.act.sum <- summarySE(sat.act, measurevar="ACT", groupvars=c("education")) 
sat.act.sum

# we use the summary we created to plot
ggplot(sat.act.sum, aes(education, ACT)) + 
  geom_bar(stat="summary", fun.y="mean") +
  ylab("Average score") +
  xlab("Education level") +
  ggtitle("Average ACT scores at each education level") +
  geom_errorbar(aes(ymin=ACT-se, ymax=ACT+se), 
                width=.2, position=position_dodge(.9)) +
  theme_classic()
```

Additional advanced suggestions for bar graphs can be found in the [supplemental materials](https://psu-psychology.github.io/r-bootcamp-2019/talks/data_visualization_supp.html#bar_graphs).

# Setting a theme

You can set a theme at any point and from that point on all graphs will use the theme supplied.

```{r}
theme_set(theme_minimal()) # sets the theme for all graphs
```

# Aesthetics (aes)

Aesthetic mappings describe how variables in the data are mapped to visual properties (aesthetics) of visualizations.

**What goes inside `aes()` and what goes outside?**  
Data goes outside aes.  
Mapping a variable in your data to an aesthetic goes inside `aes()` (e.g. having the points' color vary based on a variable in the data).  
Setting an aesthetic to a single value can go outside `aes()` (e.g. making all the points red).  

**When do aesthetic mappings go inside `ggplot()` vs inside `geom_*()`?**  
If you want the aesthetic mapping to apply to all the geoms, put it inside ggplot(). If you want it to apply only to a single geom, put it inside `geom_*()`.   

**What aesthetics are there?**  

## Color/fill 
Both change the color, but different geoms use one or the other or both.

This can be categorical:
```{r color-dichot}
ggplot(sat.act, aes(x = SATV, y = SATQ, color = sex)) + 
  geom_point()

ggplot(sat.act, aes(x = SATV, fill = sex)) + 
  geom_density(alpha = .5)
```

or continuous:
```{r color-cont}
ggplot(sat.act, aes(x = SATV, y = SATQ, color = age)) + 
  geom_point() +
  scale_color_continuous(low = "lightblue", high = "darkblue")
```

## Size

```{r size}
ggplot(sat.act, aes(x = SATV, y = SATQ, size = age)) + 
  geom_point() +
  scale_size_continuous(range = c(.5,3))
```

## Shape

```{r shape}
ggplot(sat.act, aes(x = SATV, y = SATQ, shape = sex)) + 
  geom_point() +
  scale_shape_manual(values = c(17, 19))
```

## Alpha (transparency)

This is often used to prevent overplotting

```{r alpha}
ggplot(sat.act, aes(x = SATV, y = SATQ)) + 
  geom_point(alpha = .6)
```

There are other aesthetic mappings for specific use cases, but these are the most common. 

# Interactions

## Dichotomous by dichotomous

Bar graph
```{r interaction-1}
ggplot(sat.act, aes(x=education, y=SATV, fill = sex)) +
  geom_bar(stat = "summary", fun.y = "mean", position = "dodge") +
  labs(fill = "Sex",
       x = "Education",
       y = "Mean SATV")
```

Does the effect of sex on SATV scores differ by education level? Maybe for people without a high school education (0). 
Additional advanced suggestions for bar graphs can be found in the [supplemental materials](https://psu-psychology.github.io/r-bootcamp-2019/talks/data_visualization_supp.html#interactions).

## Dichotomous by continuous

Scatter plot with best fit lines
```{r interaction-2}
ggplot(sat.act, aes(x = SATV, y = SATQ, color = sex)) + 
  geom_point() +
  geom_smooth(method = "lm", se = F)
```

Does the effect of SATV on SATQ differ by sex? Not a large visual difference between the best fit lines for each sex.  

## Continuous by continuous

Scatter plot with lines for specified values of the continuous moderator (+/- 1 SD by default).
Uses the `interactions` package.

```{r interaction-3}
# First run your model
lm1 <- lm(ACT~SATQ*SATV, sat.act) 

# Provide that model to the interact_plot function
interactions::interact_plot(lm1, pred = SATQ, modx = SATV,
              plot.points = TRUE,
              x.label = "SATQ",
              y.label = "ACT",
              legend.main = "SATV")
```

Is there an interaction between SATQ and SATV in predicting ACT? Looks like it! As SATV scores increase, the relationship between SATQ and ACT becomes stronger.

## Three-way interaction

Use faceting

```{r interaction-4}
plot <- ggplot(sat.act, aes(x=SATQ, y=SATV, color = sex)) +
  geom_point(alpha = .6) +
  stat_smooth(method = lm, se = FALSE, size = 1.2) +
  facet_wrap(vars(education))
plot
```

# Finishing touches

Axis titles, labels and breaks, plot title, plot caption, font sizes, theme, gridlines, axis lines, facet spacing, legend positioning, etc... All the fiddly details.

```{r finish}
plot +
  labs(title = "Relationship between SATQ and SATV by sex and education",
       subtitle = "Data from SAPA project",
       caption = "N = 687") + 
  scale_y_continuous(breaks = seq(200, 800, by = 100)) +
  theme_bw() +
  theme(panel.grid.minor.x = element_blank(),
        panel.grid.minor.y = element_blank()) +
  theme(axis.text = element_text(size = 10),
        axis.title = element_text(size = 13),
        legend.text = element_text(size = 11),
        legend.title = element_text(size = 13)) +
  theme(panel.spacing.x = unit(1, "lines")) + 
  theme(legend.title = element_blank())
```

# Exporting plots

`ggsave` easily exports plots in a variety of file formats, to your specified dimensions and resolution.    
You can export a saved plot object, or if no plot is specified, it will export the last plot you produced. 

```{r export, eval=FALSE}
ggsave("plot.png",
       width = 10, height = 6, dpi = 300) # make a 10 x 6 inch PNG file with 300 DPI
```
