---
title: "Exploring data"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Exploring data}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include = FALSE}
knitr::opts_chunk$set(collapse = FALSE, comment = "",
                      fig.width = 7, fig.height = 4.5, dpi = 96,
                      dev.args = list(bg = "transparent"))
# Console colour carries no meaning on a rendered page. pkgdown turns it on for
# its own build, and the escape sequences then reach the reader as literal text,
# so colour is switched off here for a plain vignette render and a site build
# alike. The fixed width keeps printed output inside the documentation column.
options(cli.num_colors = 1, cli.hyperlink = FALSE, crayon.enabled = FALSE,
        width = 80)

# Figures on the package website sit on a warm off-white page in light mode and
# are inverted by pkgdown in dark mode, so an opaque background would read as a
# pale slab one way and a black plate the other. Two things paint one. The
# device canvas is made transparent by `dev.args` above, and theme_depictr()
# then inherits theme_minimal()'s white plot.background, which is drawn over
# that canvas, so it is cleared as each figure is printed. This is deliberately
# a vignette-level choice: theme_depictr() keeps its opaque background, which
# is what a figure saved for a paper wants.
transparent_bg <- ggplot2::theme(
  plot.background  = ggplot2::element_rect(fill = NA, colour = NA),
  panel.background = ggplot2::element_rect(fill = NA, colour = NA)
)
knit_print.ggplot <- function(x, ...) knitr::normal_print(x + transparent_bg)
knit_print.patchwork <- function(x, ...) knitr::normal_print(x & transparent_bg)

library(depictr)
```

depictr provides exploratory plots, estimation plots and a descriptive table.
The plots share the package theme and palette. An argument that names one
column, such as `x`, `y` or `group`, takes it quoted or unquoted. One that names
several, such as `cols`, takes a character vector, and `summary_table()` takes
its `vars` and `group` as strings. The examples use the bundled
`lexical_decision`, `wellbeing_survey` and `crop_yield` datasets. A closing
section shows how to customise any of these plots with ordinary ggplot2 code.

## One variable

`explore_distribution()` plots a numeric variable and `explore_categorical()` a
categorical one. A unimodal density leaves its upper corners empty, so
`legend_inside = TRUE` moves the colour legend from the right-hand margin into
the top-right corner. Several plots take this argument, and it is off by default
because the empty corner depends on the data.

```{r}
explore_distribution(lexical_decision, RT, group = condition, type = "density",
                     legend_inside = TRUE)
```

An overlay gets crowded once there are several groups, so `facet = TRUE` gives
each group its own panel:

```{r}
explore_distribution(wellbeing_survey, life_satisfaction, group = region,
                     type = "both", facet = TRUE)
```

`ecdf_plot()` is a bin-free alternative. The empirical cumulative distribution
lets you read medians and quantiles off the curve and makes a shift between
groups obvious. Here the related condition is faster throughout.

```{r}
ecdf_plot(lexical_decision, RT, group = condition,
          reference_quantiles = c(0.25, 0.5, 0.75), legend_inside = TRUE)
```

```{r}
explore_categorical(wellbeing_survey, education, group = region,
                    proportion = TRUE, position = "dodge")
```

## Two variables, any types

`explore_bivariate()` chooses the plot from the variable types: a scatter plot
for two numeric variables, box plots for a numeric variable against a
categorical one, and a filled bar chart for two categorical variables.

```{r}
explore_bivariate(lexical_decision, condition, RT)
```

For a focused scatter with a fitted trend, use `scatter_trend()`. The
data-generating process of `crop_yield` contains a fertiliser-by-treatment
interaction, visible here as two diverging slopes.

```{r}
scatter_trend(crop_yield, fertiliser, yield, group = treatment)
```

## Many variables at once

`explore_pairs()` is a scatter-plot matrix, and `correlation_heatmap()`
condenses the same information into a single coloured grid.

```{r, fig.height = 6}
explore_pairs(crop_yield,
              cols = c("rainfall", "fertiliser", "soil_ph", "yield"))
```

```{r, fig.height = 5}
correlation_heatmap(wellbeing_survey)
```

`reorder = TRUE` orders the variables by hierarchical clustering, so blocks of
mutually correlated variables sit together:

```{r, fig.height = 5}
correlation_heatmap(wellbeing_survey, reorder = TRUE)
```

## Distributions across groups

`raincloud_plot()` shows the density, the box summary and the raw points
together. `group_comparison_plot()` draws the group means with confidence
intervals over the raw data. Because it shows each estimate with its
uncertainty, it conveys more faithfully than a bar chart whether the groups
differ.

```{r}
raincloud_plot(lexical_decision, RT, group = condition)
```

```{r}
group_comparison_plot(lexical_decision, RT, condition)
```

To compare the *shape* of a distribution across several groups at once,
`ridgeline_plot()` stacks one partially overlapping density per group:

```{r, fig.height = 4}
ridgeline_plot(wellbeing_survey, life_satisfaction, region)
```

## Estimation plots: effect size rather than a p-value

An *estimation plot* puts the effect size and its uncertainty at the centre of
the comparison. `estimation_plot()` draws a Cumming estimation plot, with the raw
data and group means on top. Beneath them, each group's difference from the
reference group is drawn with a bootstrap confidence interval, in that group's
column. Each difference is annotated with a standardised effect size (Hedges'
*g* by default).

```{r, fig.height = 5}
set.seed(1)
estimation_plot(lexical_decision, RT, condition,
                title = "RT difference: unrelated vs. related priming")
```

`group_comparison_plot(differences = TRUE)` turns the group-means plot into an
estimation plot by appending the difference panel. With more than two groups,
every other group is compared against a chosen reference.

```{r, fig.height = 5}
set.seed(1)
group_comparison_plot(crop_yield, yield, treatment, differences = TRUE,
                      title = "Yield difference: enhanced vs. standard")
```

## Comparing two groups across categories

`dumbbell_plot()` compares one value between two groups across a set of
categories. A segment joins the two group values in each category and shows
the size and direction of the gap. Here the plot contrasts younger and older
respondents' life satisfaction by region.

```{r}
wb <- wellbeing_survey
wb$age_group <- ifelse(wb$age < median(wb$age), "younger", "older")
dumbbell_plot(wb, region, life_satisfaction, age_group, legend_inside = TRUE)
```

## Data quality: outliers and missingness

`outlier_plot()` draws the distribution as a box or violin plot and highlights
the points beyond the 1.5 * IQR fences. Use it to check for unusual values
before modelling.

```{r}
outlier_plot(crop_yield, yield)
```

`wellbeing_survey` has *informative* missingness, with income missing more
often at higher stress, so its missingness map is worth checking before
modelling.

```{r, fig.height = 5}
missingness_map(wellbeing_survey, legend_inside = TRUE)
```

## A descriptive summary table

`summary_table()` builds a 'Table 1': mean (SD) for numeric variables, counts
and percentages for categorical ones, optionally by group. The first row always
reports the sample size (`N`), and any variable with missing values gets a
`Missing, n (%)` row. The `wellbeing_survey` table below shows both.
`summary_table()` returns a plain data frame, ready for `knitr::kable()`.

```{r}
tab <- summary_table(
  wellbeing_survey,
  vars = c("life_satisfaction", "income", "stress", "education"),
  group = "region"
)
knitr::kable(tab)
```

## Customising and extending the plots

Every depictr plotting function returns a plain `ggplot2` object, or a
`patchwork` for a composite figure, so you can keep adding layers, scales,
labels and theme tweaks with the usual `+`:

```{r}
library(ggplot2)

scatter_trend(crop_yield, fertiliser, yield, group = treatment) +
  labs(title = "Yield rises with fertiliser",
       subtitle = "More steeply under the enhanced treatment") +
  theme(legend.position = "bottom")
```

### Tidying the legend

depictr centres a legend title over its keys by default. When the level names
are self-explanatory, drop the title by setting it to `NULL`. Reversing a
discrete colour legend at the same time makes it read top-to-bottom in the order
the curves are stacked:

```{r}
ecdf_plot(lexical_decision, RT, group = condition) +
  labs(colour = NULL) +
  guides(colour = guide_legend(reverse = TRUE))
```

### Moving the legend into the plot

Several plots take `legend_inside = TRUE` to place the legend in a corner they
usually leave empty (see e.g. `?ecdf_plot`). For any other plot, one `theme()`
call does the same. A dodged bar chart, for instance, leaves the top-right clear
when the right-most category is short, so the legend fits there. We drop the
title too, as the region names are self-explanatory, and use `element_blank()`
because this plot sets the legend name on its fill scale:

```{r}
explore_categorical(wellbeing_survey, education, group = region,
                    proportion = TRUE, position = "dodge") +
  theme(legend.position = "inside",
        legend.position.inside = c(0.98, 0.98),
        legend.justification = c(1, 1),
        legend.title = element_blank())
```

### Built-in layout controls

Many functions also have layout controls of their own.
`explore_distribution(facet = TRUE)` and `ridgeline_plot()` separate groups,
`correlation_heatmap(reorder = TRUE)` clusters variables, and the model-estimate
plots take `facet` to keep coefficients on very different scales legible.
`coefficient_plot()` also takes `standardise` to the same end (see
`vignette("model-estimates")`).
