---
title: "ggformula/lattice Comparison"
author: "Nicholas Horton (nhorton@amherst.edu)"
date: '`r Sys.Date()`'
vignette: |
  %\VignetteIndexEntry{ggformula/lattice Comparison} 
  \usepackage[utf8]{inputenc}
  %\VignetteEngine{knitr::rmarkdown} 
output: 
  html_document:
    fig_height: 2.6
    fig_width: 5
  pdf_document:
    fig_height: 2.4
    fig_width: 5
    pandoc_args: ["-V", "classoption=twocolumn"]
  word_document:
    fig_height: 2.6
    fig_width: 5
---

```{r, setup, include = FALSE}
require(mosaic)   # Load additional packages here 
require(ggformula)

# Some customization.  You can alter or delete as desired (if you know what you are doing).
trellis.par.set(theme = theme.mosaic()) # change default color scheme for lattice
theme_set(theme_bw())                   # change default theme for ggformula
knitr::opts_chunk$set(
  tidy = FALSE,     # display code as typed
  size = "small")   # slightly smaller font for code
```

## Introduction

This document is intended to help users of the `mosaic` package migrate their `lattice` package graphics to `ggformula`.  The mosaic package provides a simplified and systematic introduction to the core functionality related to descriptive statistics, visualization, modeling, and simulation-based inference required in first and second courses in statistics.  

\newpage

\vspace*{.10in}
Originally, the `mosaic` package used `lattice` graphics but now support is also available for the improved `ggformula` system.  Going forward, `ggformula` will be the preferred graphics 
package for Project MOSAIC.

\vfill

\newpage

## Histograms 

<div class = "row">
<div class = "col-md-6">

### Histograms (ggformula)

```{r, hist-gg}
library(mosaic)   # also loads ggformula 
gf_histogram(~ age, data = HELPrct)
```

### Histogram options (ggformula)

```{r, hist-opt-gg}
gf_histogram(~ age, data = HELPrct,
             binwidth = 5) 
```


</div>
\newpage
\vspace*{.03in}

<div class = "col-md-6">
### Histograms (lattice)

```{r, hist-lattice}
library(mosaic)     # also loads lattice
histogram(~ age, data = HELPrct)
```

### Histogram options (lattice)

```{r, hist-opt-lattice}
histogram(~ age, width = 5, data = HELPrct)
```


</div>
</div>

\newpage

## Density Plots

<div class = "row">
<div class = "col-md-6">

### Density plots (ggformula)

```{r, dens-gg, message = FALSE}
gf_dens(~ age, data = HELPrct)
```

### Overlaid density plots (ggformula)

```{r, dens2-gg, message = FALSE}
gf_dens(~ age, data = HELPrct,
        color = ~ sex)
```

### Density over histograms (ggformula)

We can use stacked layers to add a density curve based on a 
maximum likelihood fit or a kernel density estimate (see also `gf_dist()`)

```{r, dens-hist-gg, message = FALSE}
gf_dhistogram( ~ age, data = HELPrct, 
               alpha = 0.5) %>%
  gf_fitdistr(color = ~"MLE", dist = "dnorm") %>% 
  gf_dens(color = ~"KDE")   
```


</div>
\newpage
\vspace*{.03in}

<div class = "col-md-6">
### Density plots (lattice)

```{r, dens-lattice, message = FALSE}
densityplot(~ age, data = HELPrct)
```

### Overlaid density plots (lattice)

```{r, dens2-lattice}
densityplot(~ age, data = HELPrct,
            groups = sex,  auto.key = TRUE)
```
### Density over histograms (lattice)

`mosaic` makes it easy to add a fitted distribution to a histogram.

```{r, dens-hist-lattice, message = FALSE}
histogram(~ age, data = HELPrct, 
          fit = "normal", dcol = "red")
```


</div>
</div>

\newpage



## Side by side boxplots 

<div class = "row">
<div class = "col-md-6">

### Side by side boxplots (ggformula)

```{r, boxplot-gg, message = FALSE}
gf_boxplot(age ~ sex, data = HELPrct)
```

### Faceted side by side boxplots (ggformula)

```{r, boxplot-facets-gg, message = FALSE}
gf_boxplot(age ~ sex | homeless, 
  data = HELPrct)
```

### Horizontal boxplots (ggformula)

```{r, boxploth-gg, message = FALSE}
gf_boxploth(sex ~ age, data = HELPrct)
```


</div>
\newpage
\vspace*{.03in}

<div class = "col-md-6">


### Side by side boxplots (lattice)

```{r, boxplot-lattice, message = FALSE}
bwplot(age ~ sex, data = HELPrct)
```

### Faceted side by side boxplots (lattice)

```{r, boxplot-facet-lattice, message = FALSE}
bwplot(age ~ sex | homeless, 
       data = HELPrct)
```

### Horizontal boxplots (lattice)

```{r, boxploth-lattice, message = FALSE}
bwplot(sex ~ age, data = HELPrct)
```

</div>
</div>

\newpage

## Scatterplots

<div class = "row">
<div class = "col-md-6">

### Basic scatterplot (ggformula)

```{r, scatter-gg, message = FALSE}
gf_point(cesd ~ age, data = HELPrct)
```



### Overlaid scatterplot with linear fit (ggformula)

```{r, scatter2-gg, message = FALSE}
gf_point(cesd ~ age, data = HELPrct,
         color = ~ sex) %>%
  gf_lm()
``````

</div>
\newpage
\vspace*{.03in}

<div class = "col-md-6">

### Basic Scatterplot (lattice)

```{r, scatter-lattice, message = FALSE}
xyplot(cesd ~ age, data = HELPrct)
```

### Overlaid scatterplot with linear fit (lattice)

```{r, scatter2-lattice, message = FALSE}
xyplot(cesd ~ age,  data = HELPrct,
       groups = sex, 
       type = c("p", "r"), 
       auto.key = TRUE) 
```


</div>
</div>

\newpage


<div class = "row">
<div class = "col-md-6">

### Faceted scatterplot with smooth fit (ggformula)

```{r, scatter3-gg, message = FALSE}
gf_point(cesd ~ age | sex, 
         data = HELPrct) %>%
  gf_smooth(se = FALSE)
``````



## More options for scatterplot with linear fit (ggformula)

```{r, scatter4-gg}
gf_point(cesd ~ age, data = HELPrct,
         color = ~ sex) %>%
  gf_lm() %>% 
  gf_theme(legend.position = "top") %>% 
  gf_labs(
    title = "This is my ggformula plot", 
    x     = "age (in years)", 
    y     = "CES-D measure of
depressive symptoms")
```


</div>
\newpage

<div class = "col-md-6">


## Faceted scatterplot with smooth fit (lattice)

```{r, scatter3-lattice, message = FALSE}
xyplot(cesd ~ age | sex,  data = HELPrct,
       type = c("p", "smooth"), 
       auto.key = TRUE) 
```




## More options for scatterplot with linear fit (lattice)

```{r, scatter4-lattice, message = FALSE}
xyplot(cesd ~ age, groups = sex, 
       type = c("p", "r"), 
       auto.key = TRUE, 
       main = "This is my lattice plot", 
       xlab = "age (in years)", 
       ylab = "CES-D measure of
depressive symptoms",
       data = HELPrct)
```

</div>
</div>

\newpage

## Refining graphs

<div class = "row">
<div class = "col-md-6">

### Log scales (ggformula)

```{r log-scales-gg}
gf_point(cesd ~ age, data = HELPrct) %>%
  gf_refine(scale_y_log10()) 
```

### Custom Colors (ggformula)

```{r refine-gg}
gf_dens(
  ~ cesd, data = HELPrct, 
  color = ~ sex) %>%
  gf_rug(
    0 ~ cesd, 
    position = position_jitter(height = 0)
  ) %>%
  gf_refine(
    scale_color_manual(
      values = c("navy", "red"))) 
```

</div>
\newpage
\vspace*{.03in}

<div class = "col-md-6">

### Log scales (lattice)

```{r, log-scales-lattice}
xyplot(
  cesd ~ age, data = HELPrct,
  scales = list(y = list(log = TRUE)))
```

### Custom Colors (lattice)

```{r, refine-lattice}
densityplot( 
  ~ cesd, data = HELPrct, groups = sex,
  rug = FALSE,
  par.settings = 
    list(
      superpose.line = 
        list(col = c("navy", "red")),
      superpose.symbol = 
        list(col = c("navy", "red"))
    )) 
```
</div>
</div>

\newpage

## Want to explore more?

Within RStudio, after loading the `mosaic` package, try running the command `mplot(ds)` where `ds` is a dataframe.  This will open up an interactive visualizer that will output the code to generate the figure (using `lattice`, `ggplot2`, or `ggformula`) when you click on `Show Expression`. 


\newpage

## References 

More information about `ggformula` can be found at https://projectmosaic.github.io/ggformula.

More information regarding Project MOSAIC (Kaplan, Pruim, and Horton) can be found at http://www.mosaic-web.org.  Further information regarding the `mosaic` package can be found at https://projectmosaic.github.io/mosaic and https://journal.r-project.org/archive/2017/RJ-2017-024.

Examples of how to bring multidimensional graphics into day one of an introductory statistics course can be found at http://escholarship.org/uc/item/84v3774z. 

\vfill






