Package 'ggseg'

Title: Plotting Tool for Brain Atlases
Description: Provides a 'ggplot2' geom and position for visualizing brain region data on cortical, subcortical, and white matter tract atlases. Brain atlas geometries are stored as polygon data, enabling seamless integration with the 'ggplot2' ecosystem including faceting, custom scales, and themes. Mowinckel & Vidal-Piñeiro (2020) <doi:10.1177/2515245920928009>.
Authors: Athanasia Mo Mowinckel [aut, cre] (ORCID: <https://orcid.org/0000-0002-5756-0223>), Didac Vidal-Piñeiro [aut] (ORCID: <https://orcid.org/0000-0001-9997-9156>), Ramiro Magno [ctb] (ORCID: <https://orcid.org/0000-0001-5226-3441>), Center for Lifespan Changes in Brain and Cognition, University of Oslo, Norway [cph]
Maintainer: Athanasia Mo Mowinckel <[email protected]>
License: MIT + file LICENSE
Version: 2.2.1.9008
Built: 2026-10-14 14:24:30 UTC
Source: https://github.com/ggsegverse/ggseg

Help Index


Add view labels to brain atlas plots

Description

Annotates each brain view with a text label positioned above the view's bounding box. For cortical atlases, labels show hemisphere and view (e.g., "left lateral"). For subcortical and tract atlases, labels show the view name directly (e.g., "axial_1", "sagittal").

Usage

annotate_brain(
  atlas,
  position = position_brain(),
  hemi = NULL,
  view = NULL,
  size = 3,
  colour = "grey30",
  family = "mono",
  padding = 0.05,
  nudge_y = 0,
  ...
)

Arguments

atlas

A brain_atlas object (e.g. dk(), aseg()).

position

The same layout you passed to geom_brain(), from position_brain(). A layout formula or one of "horizontal", "vertical", "identity" is accepted too, and coerced exactly as geom_brain() coerces it.

hemi

Character vector of hemispheres to include. If NULL (default), all hemispheres are included.

view

Character vector of views to include. If NULL (default), all views are included.

size

Text size in mm (default: 3).

colour

Text colour (default: "grey30").

family

Font family (default: "mono").

padding

Vertical gap between each label and its view, as a fraction of the plot's total height (default: 0.05). Labels are also bottom-anchored (vjust = 0) so they sit clear of the geometry.

nudge_y

Additional absolute vertical offset for labels (default: 0).

...

Additional arguments passed to ggplot2::annotate().

Details

Pass the same position you gave geom_brain() and the labels line up with the views automatically.

Value

A ggplot2 annotation layer.

Examples

library(ggplot2)

pos <- position_brain(hemi ~ view)
ggplot() +
  geom_brain(atlas = dk(), position = pos, show.legend = FALSE) +
  annotate_brain(atlas = dk(), position = pos)

ggplot() +
  geom_brain(atlas = dk(), show.legend = FALSE) +
  annotate_brain(atlas = dk())

Join user data with a brain atlas

Description

Matches your data to a brain atlas by a shared column (usually region), keeping every atlas region whether or not you have a value for it. Grouped data (via dplyr::group_by()) gives one complete atlas per group. You rarely need this directly – geom_brain() joins your data for you; reach for brain_join() when you want the joined sf object yourself.

Usage

brain_join(data, atlas, by = NULL)

Arguments

data

A data.frame with a column matching an atlas column (typically "region"). Can be grouped with dplyr::group_by().

atlas

A ggseg_atlas object or data.frame containing atlas data.

by

Character vector of column names to join by. If NULL (default), columns are detected automatically.

Value

An sf object if the atlas contains geometry, otherwise a tibble.

Examples

someData <- data.frame(
  region = sort(unique(ggseg.formats::atlas_regions(dk())))[1:4],
  p = sample(seq(0, .5, .001), 4),
  stringsAsFactors = FALSE
)

brain_join(someData, dk())
brain_join(someData, dk(), "region")

Render a brain atlas with default snapshot styling

Description

Builds a minimal, deterministic plot of a ggseg_atlas: every region filled by its label, no legend, and ggplot2::theme_void(). This is the canonical construction used across the ggsegverse for visual-regression (vdiffr) snapshots, so that every atlas is rendered the same way and a stray legend, axis, or title cannot creep into a snapshot. It doubles as a quick way to preview an atlas.

Usage

brain_test_plot(atlas, position = NULL, na.value = "grey")

Arguments

atlas

A ggseg_atlas object, such as dk() or aseg().

position

A ggplot2 position adjustment arranging the brain views. Defaults to position_brain(hemi ~ view) for cortical atlases and position_brain(. ~ view) for slice-based atlases (subcortical, cerebellar, tract), whose views already contain both hemispheres.

na.value

Fill colour for regions with no palette entry. Defaults to "grey".

Details

The atlas palette is applied with ggplot2::scale_fill_manual() when it is present; atlases without a palette fall back to the default ggplot2 fill scale.

Value

A ggplot2::ggplot() object.

See Also

geom_brain()

Examples

brain_test_plot(dk())

Keep brain shapes undistorted

Description

Fixes the aspect ratio so brains aren't stretched by the shape of the plotting window. geom_brain() adds coord_brain() for you, so you rarely need to call it yourself – reach for it only to adjust the ratio or clip behaviour. You can safely add your own coord or stack several geom_brain() layers; it steps aside cleanly.

Usage

coord_brain(ratio = 1, clip = "off", ...)

Arguments

ratio

Aspect ratio, expressed as y / x. Defaults to 1, which keeps brain polygons undistorted.

clip

Should drawing be clipped to the panel extent ("on") or allowed to overflow ("off")? Defaults to "off" so region outlines at the panel edge are not cut.

...

Additional arguments passed to ggplot2::coord_fixed().

Value

A ggplot2 coordinate system that registers as a default.

Examples

library(ggplot2)
## Not run: 
poly <- ggseg.formats::as_polygon_atlas(dk())
# Equivalent to the default; shown explicitly:
ggplot() +
  geom_brain(atlas = poly, show.legend = FALSE) +
  coord_brain()

## End(Not run)

Plot brain atlas regions

Description

Colour brain regions by your own values. Give geom_brain() an atlas like dk() and a data frame, and it matches your values to the right regions and lays out the brain views for you. No data? It just draws the atlas.

Usage

geom_brain(
  mapping = aes(),
  data = NULL,
  atlas,
  hemi = NULL,
  view = NULL,
  position = position_brain(),
  context = TRUE,
  fun = mean,
  show.legend = NA,
  inherit.aes = TRUE,
  ...
)

Arguments

mapping

Set of aesthetic mappings created by ggplot2::aes().

data

A data.frame containing variables to map. If NULL, the atlas is plotted without user data. Add a facet with ggplot2::facet_wrap() to draw one brain per group.

atlas

A ggseg_atlas object (e.g. dk(), aseg(), tracula()).

hemi

Character vector of hemispheres to include (e.g. "left", "right"). Defaults to all hemispheres in the atlas.

view

Character vector of views to include, as recorded in the atlas data. For cortical atlases: "lateral", "medial". For subcortical/tract atlases: slice identifiers like "axial_3". Defaults to all views.

position

Brain-view layout: the result of a call to position_brain(), a layout string (e.g. "horizontal", "vertical"), or a layout formula (e.g. hemi ~ view). Strings and formulas are passed to position_brain(). Use "identity" to keep the atlas polygons' raw coordinates. Per-view zoom is set through position_brain()'s zoom.

context

Keep the rest of the brain as a soft grey backdrop (TRUE, the default), or show only the regions you're plotting (FALSE).

fun

Function used to combine multiple data rows that map to the same atlas region, applied within each facet panel. Defaults to mean(). Any function reducing a vector to a single value works (e.g. median(), max()). It applies to numeric columns only; non-numeric ones take the first value of the group. Up to ggseg 2.2.1 duplicate rows overplotted, so the last one won — fun = dplyr::last reproduces that.

show.legend

Logical. Should this layer be included in the legends?

inherit.aes

Logical. If FALSE, overrides the default aesthetics rather than combining with them.

...

Additional arguments passed to ggplot2::geom_polygon().

Details

Map neither fill nor colour and geom_brain() colours the atlas by its own palette for you, by mapping fill to label – the key atlas palettes are built on, and the ecosystem's canonical matching key. Map either one and yours wins; your data then drives the colours and regions you supply no value for stay grey.

Match your data to the atlas on label (hemisphere-qualified, unique per atlas row) or on region (which repeats across hemispheres).

Regions are drawn in the order they appear in your data, so when outlines overlap (e.g. mapping colour to a threshold with a wide linewidth) the later rows draw on top. Reorder your data with dplyr::arrange() to control the layering; regions you supply no value for stay underneath in atlas order.

Faceting works without any dplyr::group_by(): the atlas geometry is drawn by StatBrain, which ggplot2 recomputes per panel, so the complete brain appears in every facet. If your data has several rows for the same region (e.g. one per subject), they are combined with fun (mean by default) before drawing.

Value

A list of ggplot2 layer and coord objects.

GeomBrain ggproto

GeomBrain is the ggplot2::Geom ggproto that renders brain atlas polygons. It subclasses ggplot2::GeomPolygon and supplies the brain defaults through default_aes – outline colour (grey35), linewidth (0.2), and fill (grey) – which apply when the user has not mapped those aesthetics but yield to a mapping when present (ggsegverse/ggseg#160). The grey default fill is what an atlas with no palette of its own falls back to; otherwise geom_brain() maps fill to label and applies the palette. Used internally by geom_brain(); not typically called directly.

StatBrain ggproto

StatBrain is the ggplot2::Stat that powers geom_brain() and stat_brain(). Its compute_panel() receives one facet panel's user data, aggregates the mapped values per atlas region with fun, and joins them onto the full atlas geometry – so every region renders in every panel whether or not you supplied a value for it. You rarely reference it directly; use it via geom_brain(..., stat = StatBrain) or stat_brain() when building a custom layer.

See Also

stat_brain() for the stat-first spelling.

Examples

library(ggplot2)

ggplot() +
  geom_brain(atlas = dk(), show.legend = FALSE)

Arrange brain atlas views

Description

Controls how an atlas's hemispheres and views are arranged in the plot – side by side, stacked, or in a grid – and can zoom each view in on the regions you care about. Pass the result to the position argument of geom_brain() (or annotate_brain()).

Usage

position_brain(
  position = "horizontal",
  nrow = NULL,
  ncol = NULL,
  views = NULL,
  zoom = NULL,
  zoom_pad = 0.05
)

Arguments

position

Formula describing the rows ~ columns organisation for cortical atlases (e.g., hemi ~ view). For subcortical/tract atlases, can be "horizontal", "vertical", or a formula with type ~ . where type is extracted from view names like "axial_1" -> "axial".

nrow

Number of rows for grid layout, a positive whole number. If NULL (default), calculated automatically. Cannot be combined with a position formula, which a grid layout would discard. Grid cells are hemisphere/view pairs for a cortical atlas and views for a slice-based one.

ncol

Number of columns for grid layout, a positive whole number. If NULL (default), calculated automatically. Cannot be combined with a position formula.

views

Character vector specifying which views to include and their order. If NULL (default), all views are included in their original order. Names the atlas does not have are dropped with a warning.

zoom

Controls per-view zoom. NULL/FALSE (default) draws each view at full extent. TRUE zooms each view onto the regions your data covers, taken from its label column when it has one and region otherwise; a character vector names the focus explicitly, as either labels or regions.

zoom_pad

Fractional padding added around the focus window when zoom is active. Defaults to 0.05 (5%).

Value

A layout specification to hand to geom_brain()'s position argument.

Examples

library(ggplot2)

# Cortical atlas with formula
ggplot() +
  geom_brain(
    atlas = dk(), aes(fill = region),
    position = position_brain(. ~ view + hemi),
    show.legend = FALSE
  )

ggplot() +
  geom_brain(
    atlas = dk(), aes(fill = region),
    position = position_brain(view ~ hemi),
    show.legend = FALSE
  )

ggplot() +
  geom_brain(
    atlas = aseg(), aes(fill = region),
    position = position_brain(nrow = 2)
  )

ggplot() +
  geom_brain(
    atlas = aseg(), aes(fill = region),
    position = position_brain(
      views = c("sagittal", "axial_3", "coronal_2"),
      nrow = 1
    )
  )

ggplot() +
  geom_brain(
    atlas = aseg(), aes(fill = region),
    position = position_brain(type ~ .)
  )

Reposition brain slices

Description

Repositions pre-joined sf atlas data (i.e. data and atlas already joined to a single sf data frame) for control over final plot layout. For even more detailed control, convert the "hemi" and "view" columns into factors ordered by wanted order of appearance.

Usage

reposition_brain(
  data,
  position = "horizontal",
  nrow = NULL,
  ncol = NULL,
  views = NULL
)

Arguments

data

sf-data.frame of joined brain atlas and data

position

Position formula for slices. For cortical atlases, use formulas like hemi ~ view. For subcortical/tract atlases, use "horizontal", "vertical", or type ~ . for type-based layout.

nrow

Number of rows for grid layout; cannot be combined with a position formula.

ncol

Number of columns for grid layout; cannot be combined with a position formula.

views

Character vector specifying view order. Names the data does not have are dropped with a warning.

Details

This is the sf layout helper. It requires the sf package (an optional dependency); for the sf-free default, build a layout with position_brain() and pass it to geom_brain().

Value

sf-data.frame with re-positioned slices

Examples

reposition_brain(dk(), hemi ~ view)
reposition_brain(dk(), view ~ hemi)
reposition_brain(dk(), hemi + view ~ .)
reposition_brain(dk(), . ~ hemi + view)


reposition_brain(aseg(), nrow = 2)
reposition_brain(aseg(), views = c("sagittal", "axial_3"))

Colour and fill scales from brain atlas palettes

Description

[Deprecated]

Atlas palettes are now applied automatically by geom_brain(). Use scale_fill_brain_manual() for custom palettes.

Usage

scale_brain(
  name = "dk",
  na.value = "grey",
  ...,
  aesthetics = c("fill", "colour", "color")
)

scale_colour_brain(name = "dk", na.value = "grey", ...)

scale_color_brain(name = "dk", na.value = "grey", ...)

scale_fill_brain(name = "dk", na.value = "grey", ...)

Arguments

name

String name of the atlas palette (e.g. "dk", "aseg").

na.value

Colour for NA entries (default: "grey").

...

Additional arguments passed to ggseg.formats::atlas_palette().

aesthetics

Which aesthetic to scale: "fill", "colour", or "color".

Value

A ggplot2 scale object.

Examples

## Not run: 
library(ggplot2)
ggplot() +
  geom_brain(atlas = dk(), aes(fill = label), show.legend = FALSE) +
  scale_brain("dk")

## End(Not run)

Manual colour and fill scales for brain plots

Description

Apply a custom named colour palette to brain atlas plots. Use this when you want to override the atlas default colours with your own colour mapping.

Usage

scale_brain_manual(
  palette,
  na.value = "grey",
  ...,
  aesthetics = c("fill", "colour", "color")
)

scale_colour_brain_manual(...)

scale_color_brain_manual(...)

scale_fill_brain_manual(...)

Arguments

palette

Named character vector mapping region names to colours.

na.value

Colour for NA entries (default: "grey").

...

Additional arguments (unused).

aesthetics

Which aesthetic to scale: "fill", "colour", or "color".

Value

A ggplot2 scale object.

Examples

library(ggplot2)

labels <- sort(unique(ggseg.formats::atlas_labels(dk())))[1:2]
pal <- setNames(c("red", "blue"), labels)
ggplot() +
  geom_brain(atlas = dk(), aes(fill = label), show.legend = FALSE) +
  scale_fill_brain_manual(palette = pal)

Deprecated scale functions

Description

[Deprecated]

These functions have been renamed for clarity:

Usage

scale_brain2(...)

scale_colour_brain2(...)

scale_color_brain2(...)

scale_fill_brain2(...)

Arguments

...

Arguments passed to the replacement function.

Value

A ggplot2 scale object.

Examples

pal <- c("transversetemporal" = "#FF0000", "insula" = "#00FF00")
suppressWarnings(scale_fill_brain2(palette = pal))

Axis and label scales for brain atlas plots

Description

Add axis labels and tick labels corresponding to brain atlas regions. These scales add hemisphere or view labels to the x and y axes based on the atlas layout.

Usage

scale_continous_brain(
  atlas = dk(),
  position = "dispersed",
  aesthetics = c("y", "x")
)

scale_x_brain(...)

scale_y_brain(...)

scale_labs_brain(atlas = dk(), position = "dispersed", aesthetics = "labs")

Arguments

atlas

A ggseg_atlas object or data.frame containing atlas data.

position

Layout style: "dispersed" (default) or "stacked".

aesthetics

Which axis to scale: "x", "y", or "labs".

...

Additional arguments passed to adapt_scales().

Value

A ggplot2 scale or labs object.

Examples

library(ggplot2)

ggplot() +
  geom_brain(atlas = dk(), show.legend = FALSE) +
  scale_x_brain() +
  scale_y_brain() +
  scale_labs_brain()

Stat-first constructor for a brain atlas layer

Description

The stat-first spelling of geom_brain(). Both build the same layer – a StatBrain that aggregates and joins your data onto the atlas geometry, drawn by geom. Reach for stat_brain() when you want to pair StatBrain with a different geom (e.g. a custom polygon geom); otherwise geom_brain() is the friendlier entry point.

Usage

stat_brain(
  mapping = aes(),
  data = NULL,
  atlas,
  hemi = NULL,
  view = NULL,
  position = position_brain(),
  context = TRUE,
  fun = mean,
  geom = GeomBrain,
  show.legend = NA,
  inherit.aes = TRUE,
  ...
)

Arguments

mapping

Set of aesthetic mappings created by ggplot2::aes().

data

A data.frame containing variables to map. If NULL, the atlas is plotted without user data. Add a facet with ggplot2::facet_wrap() to draw one brain per group.

atlas

A ggseg_atlas object (e.g. dk(), aseg(), tracula()).

hemi

Character vector of hemispheres to include (e.g. "left", "right"). Defaults to all hemispheres in the atlas.

view

Character vector of views to include, as recorded in the atlas data. For cortical atlases: "lateral", "medial". For subcortical/tract atlases: slice identifiers like "axial_3". Defaults to all views.

position

Brain-view layout: the result of a call to position_brain(), a layout string (e.g. "horizontal", "vertical"), or a layout formula (e.g. hemi ~ view). Strings and formulas are passed to position_brain(). Use "identity" to keep the atlas polygons' raw coordinates. Per-view zoom is set through position_brain()'s zoom.

context

Keep the rest of the brain as a soft grey backdrop (TRUE, the default), or show only the regions you're plotting (FALSE).

fun

Function used to combine multiple data rows that map to the same atlas region, applied within each facet panel. Defaults to mean(). Any function reducing a vector to a single value works (e.g. median(), max()). It applies to numeric columns only; non-numeric ones take the first value of the group. Up to ggseg 2.2.1 duplicate rows overplotted, so the last one won — fun = dplyr::last reproduces that.

geom

The geometric object used to render the atlas. Defaults to GeomBrain.

show.legend

Logical. Should this layer be included in the legends?

inherit.aes

Logical. If FALSE, overrides the default aesthetics rather than combining with them.

...

Additional arguments passed to ggplot2::geom_polygon().

Value

A list of ggplot2 layer and coord objects.

See Also

geom_brain()

Examples

library(ggplot2)

# Equivalent to geom_brain(atlas = dk())
ggplot() +
  stat_brain(atlas = dk(), show.legend = FALSE)

Themes for brain atlas plots

Description

A set of ggplot2 themes designed for brain atlas visualisations. All themes remove axis ticks and grid lines for a clean presentation.

Usage

theme_brain(text.size = 12, text.family = "mono")

theme_darkbrain(text.size = 12, text.family = "mono")

theme_custombrain(
  plot.background = "white",
  text.colour = "darkgrey",
  text.size = 12,
  text.family = "mono"
)

theme_brain2(
  plot.background = "white",
  text.colour = "darkgrey",
  text.size = 12,
  text.family = "mono"
)

Arguments

text.size

Text size in points (default: 12).

text.family

Font family (default: "mono").

plot.background

Background fill colour (theme_custombrain and theme_brain2 only).

text.colour

Text colour (theme_custombrain and theme_brain2 only).

Details

theme_brain

Default theme. Transparent background, no axes, no grid.

theme_darkbrain

Dark theme with black background and light text.

theme_custombrain

Fully customisable background, text colour, size, and font.

theme_brain2

Like theme_custombrain but with axis text removed entirely.

Value

A ggplot2::theme object.

See Also

geom_brain(), ggplot2::theme()

Examples

library(ggplot2)

p <- ggplot() +
  geom_brain(atlas = dk(), show.legend = FALSE)

p +
  theme_brain()

p +
  theme_darkbrain()