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

```{r}
#| label: setup
#| include: false
knitr::opts_chunk$set(eval = TRUE, fig.retina = 3, fig.width = 6)
```

Most of the time, you're not plotting empty atlases. You have results --
p-values, cortical thickness, whatever -- and you want them on a brain. This
vignette covers how to get your data into the right shape for ggseg.

```{r}
#| label: load-packages
library(ggseg)
library(dplyr)
library(ggplot2)
```

## How matching works

`geom_brain()` joins your data to the atlas by `region` (and by
`hemi` too, when both your data and the atlas carry it). That means your data
needs at least one column with names that match the atlas. The two columns
you'll use most:

- **region** -- human-readable names like "insula" or "precentral"
- **label** -- FreeSurfer labels like "lh_bankssts"

Check what's available:

```{r}
#| label: dk-regions
ggseg.formats::atlas_regions(dk())
```

```{r}
#| label: dk-labels
ggseg.formats::atlas_labels(dk())
```

Names must match exactly, including case and spacing.

## A minimal example

Three regions, three p-values:

```{r}
#| label: minimal-data
some_data <- tibble(
  region = c("superior temporal", "precentral", "lateral orbitofrontal"),
  p = c(0.03, 0.6, 0.05)
)
some_data
```

Pass the data to `geom_brain()` through its `data` argument and map
`fill` to your variable:

```{r}
#| label: fig-minimal-plot
#| fig-cap: "Brain plot with three regions coloured by p-value."
ggplot() +
  geom_brain(atlas = dk(), data = some_data, mapping = aes(fill = p))
```

Regions not in your data appear as `NA` (grey by default). Regions in your
data that don't match the atlas are silently dropped, so watch your spelling.

## Constraining matches with extra columns

If your data is hemisphere-specific, add a `hemi` column. The join will use
both `region` and `hemi`, so values only land on the correct side:

```{r}
#| label: fig-hemi-constraint
#| fig-cap: "Brain plot restricted to the left hemisphere using a hemi column."
some_data$hemi <- "left"

ggplot() +
  geom_brain(atlas = dk(), data = some_data, mapping = aes(fill = p))
```

The same works for any atlas column -- adding `view`, for instance, would
restrict matches to specific views.

## Faceting across groups

If your data has a grouping variable, group by it and `facet_wrap()` /
`facet_grid()` work as you'd expect. `geom_brain()` replicates the
full atlas -- context regions included -- in each panel:

```{r}
#| label: fig-facet-groups
#| fig-cap: "Brain plots faceted by age group with a custom colour gradient."
some_data <- tibble(
  region = rep(
    c(
      "transverse temporal",
      "insula",
      "precentral",
      "superior parietal"
    ),
    2
  ),
  p = sample(seq(0, 0.5, 0.001), 8),
  group = c(rep("Young", 4), rep("Old", 4))
)

ggplot() +
  geom_brain(
    atlas = dk(),
    data = group_by(some_data, group),
    colour = "white",
    mapping = aes(fill = p)
  ) +
  facet_wrap(~group, ncol = 1) +
  theme(legend.position = "bottom") +
  scale_fill_gradientn(
    colours = c("royalblue", "firebrick", "goldenrod"),
    na.value = "grey"
  )
```

Grouping the data is what tells the geom how many copies of the atlas to
make -- one per group.

## Troubleshooting

**Regions don't show up.** Check spelling and case. `ggseg.formats::atlas_regions(dk())`
gives you the exact strings the atlas expects.

**Data lands on both hemispheres.** Add a `hemi` column with `"left"` or
`"right"` to constrain the match.

**A facet panel is missing context.** Group your data by the faceting
variable before plotting (`data = my_data |> group_by(group)`) so the full
atlas is replicated in every panel.

## Full control with sf

When you need to layer brain data with other sf geoms, or join the atlas
manually before plotting, work with the atlas as an sf object instead. See
`vignette("geom-sf")` for that workflow.
