| Title: | Create Images of Volumetric Brain Data in NIfTI Format Using 'ggplot2' Syntax |
|---|---|
| Description: | A 'ggplot2'-consistent approach to generating 2D displays of volumetric brain imaging data. Display data from multiple NIfTI images using standard 'ggplot2' conventions such scales, limits, and themes to control the appearance of displays. The resulting plots are returned as 'patchwork' objects, inheriting from 'ggplot', allowing for any standard modifications of display aesthetics supported by 'ggplot2'. |
| Authors: | Michael Hallquist [aut, cre] (ORCID: <https://orcid.org/0000-0001-5894-8038>) |
| Maintainer: | Michael Hallquist <[email protected]> |
| License: | GPL (>= 3) |
| Version: | 0.9.2 |
| Built: | 2026-06-02 22:33:58 UTC |
| Source: | https://github.com/michaelhallquist/ggbrain |
addition operator for ggb object to support ggplot-like syntax
## S3 method for class 'ggb' o1 + o2## S3 method for class 'ggb' o1 + o2
o1 |
the first object inheriting the ggb class |
o2 |
the second object inheriting the ggb class |
Note that the addition operator always clones the underlying o1 object rather than modifying it in place
a modified version of the o1 object with o2 added to it
summary S3 method for ggbrain_images objects addition operator for combining ggbrain_images objects
## S3 method for class 'ggbrain_images' o1 + o2## S3 method for class 'ggbrain_images' o1 + o2
o1 |
first ggbrain_images object |
o2 |
second ggbrain_images object |
note that the addition does not modify either existing object. Rather, the first object is cloned and the second is added to it. If you want to add one ggbrain_images object to another in place (i.e., modifying the extant object), use the $add() method.
combined ggbrain_images object
Adds the coordinate labels to each panel based on the location of the slice along the slicing axis (e.g., z = 15)
annotate_coordinates(x = "right", y = "bottom", ...)annotate_coordinates(x = "right", y = "bottom", ...)
x |
the x position of the coordinate label. If numeric, it is assumed to be the pixel position along the x axis (e.g., 26).
In addition, convenience values of |
y |
the y position of the coordinate label. If numeric, it is assumed to be the pixel position along the y axis (e.g., 26).
In addition, convenience values of 'top', |
... |
any other arguments to ggplot2::annotate, which will be passed through to each panel |
a ggb object with the action 'add_annotations', used in a ggbrain addition chain
Annotate crosshairs at user-specified world (xyz) coordinates
annotate_crosshairs( xyz, color = "white", linewidth = 0.4, alpha = 0.7, linetype = "dashed", tol = 1, ... )annotate_crosshairs( xyz, color = "white", linewidth = 0.4, alpha = 0.7, linetype = "dashed", tol = 1, ... )
xyz |
A numeric matrix or data.frame with columns |
color |
Line color for the crosshairs. Default: "white". |
linewidth |
Line width passed to |
alpha |
Line alpha. Default: 0.7. |
linetype |
Line type (e.g., "dashed"). Default: "dashed". |
tol |
Tolerance (in mm) for matching a coordinate to a displayed slice along its slicing axis. Default: 1. |
... |
Additional arguments passed to |
Crosshairs are drawn on slices whose slicing axis (e.g., z for axial) falls within
tol mm of the requested coordinate. If the coordinate on the slicing axis is NA,
the crosshair is shown on all slices along that axis where the remaining two axes match.
For example, x=0, y=0, z=NA will show a crosshair on every axial slice at x/y=0 (within
the nearest in-plane voxel). Coordinates are provided in world space to match the
slices() API.
A ggb object with action "add_annotations"
## Not run: # Show crosshairs on any axial slice at x/y = 0 ggbrain() + images(c(underlay = underlay_2mm)) + slices(c("z = 20", "z = 40")) + geom_brain("underlay") + annotate_crosshairs(data.frame(x = 0, y = 0, z = NA), linewidth = 0.6) ## End(Not run)## Not run: # Show crosshairs on any axial slice at x/y = 0 ggbrain() + images(c(underlay = underlay_2mm)) + slices(c("z = 20", "z = 40")) + geom_brain("underlay") + annotate_crosshairs(data.frame(x = 0, y = 0, z = NA), linewidth = 0.6) ## End(Not run)
Annotate orientation labels (L/R/A/P/S/I) on each panel using NIfTI header info
annotate_orientation(size = 3, color = NULL, offset = 0, show = "all", ...)annotate_orientation(size = 3, color = NULL, offset = 0, show = "all", ...)
size |
Text size passed to ggplot2::annotate |
color |
Text color passed to ggplot2::annotate. If NULL, defaults to the panel text color. |
offset |
Offset to nudge labels away from the image edge. Can be scalar or length 4 (left, right, bottom, top). Numeric values are in data units; percentage strings (e.g., "10%") are interpreted relative to the panel width (left/right) or height (bottom/top). |
show |
Character vector of labels to display. Valid values are any of |
... |
Additional arguments passed to ggplot2::annotate (e.g., fontface) |
Uses RNifti::orientation on the first image in the ggbrain object (cached in the slices object) to infer axis labels and places them along the edges of each panel. If orientation cannot be determined, no annotations are added.
a ggb object with action "add_annotations"
Adds custom annotations to a single panel on the ggbrain plot
annotate_slice(slice_index = NULL, ...)annotate_slice(slice_index = NULL, ...)
slice_index |
the slice number to which this annotation is added. These are numbered in the wrapping order from patchwork::wrap_plots, which will normally go from top-left to bottom-right. |
... |
Additional parameters passed to ggplot2::annotate such as |
For annotation coordinates such as x, y, or xmin, you may pass in a number. In this case, the value specifies the pixel
position along the relevant axis (e.g., x=26). In addition, convenience values of 'left', 'right', and 'middle' can be used
for the x axis, and 'top', 'bottom', and 'middle' for the y axis.
Finally, or 'q[1-100]' can be used to look up the quantile-based positions along the relevant axis. For example,
x="q25" would position the annotation at the 25% mark along the x axis.
N.B. This function only adds a single annotation on a single panel!
a ggb object with the relevant annotations field and an action of "add_annotations"
This function identifies connected clusters in a brain image (after applying an optional definition/contrast) and returns slice coordinates corresponding to the center of mass of each cluster. This is useful for automatically selecting slices that display the most relevant activation clusters.
cluster_slices( images = NULL, layer = NULL, definition = NULL, nclusters = 10, min_clust_size = 1, plane = "axial", nn = 3, outline = FALSE, outline_color = NULL, outline_size = 1L, outline_scale = NULL, outline_show_legend = NULL, sided = c("bisided", "two_sided") )cluster_slices( images = NULL, layer = NULL, definition = NULL, nclusters = 10, min_clust_size = 1, plane = "axial", nn = 3, outline = FALSE, outline_color = NULL, outline_size = 1L, outline_scale = NULL, outline_show_legend = NULL, sided = c("bisided", "two_sided") )
images |
A ggbrain_images object or a named character vector of image file paths. Required for computing cluster locations. |
layer |
The name of a geom_brain layer whose definition should be used for clustering.
Mutually exclusive with |
definition |
A definition string (same syntax as geom_brain) specifying the image/contrast
to use for clustering. Examples: |
nclusters |
Maximum number of clusters to return slices for. Clusters are sorted by
size (descending), and the top |
min_clust_size |
Minimum cluster size in voxels. Clusters smaller than this are ignored. Default: 1 |
plane |
The plane for slice selection: |
nn |
Neighborhood connectivity for defining clusters. Must be 1, 2, or 3:
Default: 3 (most inclusive) |
outline |
Logical. If |
outline_color |
A single color string for all cluster outlines. If |
outline_size |
Integer specifying the outline thickness in pixels. Default: 1 |
outline_scale |
A ggplot2 scale object (e.g., |
outline_show_legend |
Logical. Whether to show a legend for cluster outlines. If
|
sided |
Sidedness for clustering thresholded images. |
The function performs 3D connected component labeling on the thresholded/masked image to identify distinct clusters. For each cluster meeting the minimum size criterion, the center of mass is computed. Slices are then selected at the center of mass coordinates along the specified plane.
When outline = TRUE, a thin outline mask is also generated for the selected clusters.
This outline can be automatically added as a geom_outline() layer during rendering so
that clusters are highlighted on each slice. By default, distinct colors are assigned to each
cluster using a categorical palette, but a single outline_color or a custom vector of
colors can also be provided. The outline thickness can be controlled via
outline_size.
The neighborhood connectivity parameter (nn) controls how voxels are considered
connected:
nn=1 (6-connectivity): Only voxels sharing a face are connected
nn=2 (18-connectivity): Voxels sharing a face or edge are connected
nn=3 (26-connectivity): Voxels sharing a face, edge, or corner are connected
If images is provided along with definition, returns a character vector
of slice coordinates (e.g., c("z = 10.5", "z = -3.2")) suitable for passing to
slices(). If layer is specified or images is not provided, returns
a deferred specification object (class "cluster_slices_spec") that will be resolved
during the ggbrain rendering pipeline.
## Not run: # Using a definition string directly t1 <- system.file("extdata", "mni_template_2009c_2mm.nii.gz", package = "ggbrain") overlay <- system.file("extdata", "pe_ptfce_fwep_0.05_2mm.nii.gz", package = "ggbrain") gg_obj <- ggbrain() + images(c(underlay = t1, overlay = overlay)) + slices(cluster_slices( images = c(overlay = overlay), definition = "overlay[abs(overlay) > 2.5]", nclusters = 5, min_clust_size = 50, plane = "axial" )) + geom_brain("underlay") + geom_brain(definition = "overlay[abs(overlay) > 2.5]") # Or defer resolution until render time (images from ggbrain pipeline) gg_obj <- ggbrain() + images(c(underlay = t1, overlay = overlay)) + slices(cluster_slices( definition = "overlay[abs(overlay) > 2.5]", nclusters = 5 )) + geom_brain("underlay") + geom_brain(definition = "overlay[abs(overlay) > 2.5]") ## End(Not run)## Not run: # Using a definition string directly t1 <- system.file("extdata", "mni_template_2009c_2mm.nii.gz", package = "ggbrain") overlay <- system.file("extdata", "pe_ptfce_fwep_0.05_2mm.nii.gz", package = "ggbrain") gg_obj <- ggbrain() + images(c(underlay = t1, overlay = overlay)) + slices(cluster_slices( images = c(overlay = overlay), definition = "overlay[abs(overlay) > 2.5]", nclusters = 5, min_clust_size = 50, plane = "axial" )) + geom_brain("underlay") + geom_brain(definition = "overlay[abs(overlay) > 2.5]") # Or defer resolution until render time (images from ggbrain pipeline) gg_obj <- ggbrain() + images(c(underlay = t1, overlay = overlay)) + slices(cluster_slices( definition = "overlay[abs(overlay) > 2.5]", nclusters = 5 )) + geom_brain("underlay") + geom_brain(definition = "overlay[abs(overlay) > 2.5]") ## End(Not run)
This function counts the number of neighboring/touching pixels in a 2D binary image
im |
A boolean matrix representing a binary image |
diagonal |
Whether to count diagonal elements as valid neighbors |
This is an internal function used by geom_outline to clean up outlines
A matrix of the same size as im containing the number of neighboring pixels
Michael Hallquist
Adds contrast definitions to the ggbrain plot
define(contrasts = NULL)define(contrasts = NULL)
contrasts |
a character vector or list containing contrasts to be computed as part of the ggbrain object definition. |
contrasts must take the form of <name> := <value expression> or must use a named vector.
Note that defining a contrast does not directly impact the appearance of the plot unless the
contrast is named in a geom_* layer.
Also note that contrasts can be specified in the definition of a layer. Thus, the define function
has two primary virtues. First, it allows for the conceptual separation of contrast definition versus usage
inside a geom_* layer, which is particularly useful if a contrast is used across several layers. Second, it allows
downstream layers to further modify the contrast, such as when we compute a
a ggb object with the relevant contrasts and an action of 'add_contrasts'
# T1-weighted template t1 <- system.file("extdata", "mni_template_2009c_2mm.nii.gz", package = "ggbrain") # signed reward prediction error map signed_pe <- system.file("extdata", "pe_ptfce_fwep_0.05_2mm.nii.gz", package = "ggbrain") # unsigned (absolute value) prediction error map abspe <- system.file("extdata", "abspe_ptfce_fwep_0.05_2mm.nii.gz", package = "ggbrain") # simple example of a difference contrast, separating definition from usage in geom_brain gg_obj <- ggbrain() + images(c(underlay = t1, signed_pe = signed_pe, abspe = abspe)) + slices(c("x = 25%", "x = 75%")) + define("signed_gt_abs := signed_pe - abspe") + geom_brain("signed_gt_abs") # you can also use a named vector in define(), which is equivalent gg_obj <- ggbrain() + images(c(underlay = t1, signed_pe = signed_pe, abspe = abspe)) + slices(c("x = 25%", "x = 75%")) + define(c(signed_gt_abs = "signed_pe - abspe")) + geom_brain("signed_gt_abs") # contrast definitions can also occur inline, yielding equivalent plots gg_obj <- ggbrain() + images(c(underlay = t1, signed_pe = signed_pe, abspe = abspe)) + slices(c("x = 25%", "x = 75%")) + geom_brain("signed_pe - abspe") # The use of contrasts() is helpful when layers modify the contrast (e.g., subsetting) gg_obj <- ggbrain() + images(c(underlay = t1, signed_pe = signed_pe, abspe = abspe)) + slices(c("x = 25%", "x = 75%")) + define(c(signed_gt_abs = "signed_pe - abspe")) + geom_brain( "signed_gt_abs[signed_gt_abs > 0]", fill_scale=ggplot2::scale_fill_distiller("Pos diff", palette = "Reds") )# T1-weighted template t1 <- system.file("extdata", "mni_template_2009c_2mm.nii.gz", package = "ggbrain") # signed reward prediction error map signed_pe <- system.file("extdata", "pe_ptfce_fwep_0.05_2mm.nii.gz", package = "ggbrain") # unsigned (absolute value) prediction error map abspe <- system.file("extdata", "abspe_ptfce_fwep_0.05_2mm.nii.gz", package = "ggbrain") # simple example of a difference contrast, separating definition from usage in geom_brain gg_obj <- ggbrain() + images(c(underlay = t1, signed_pe = signed_pe, abspe = abspe)) + slices(c("x = 25%", "x = 75%")) + define("signed_gt_abs := signed_pe - abspe") + geom_brain("signed_gt_abs") # you can also use a named vector in define(), which is equivalent gg_obj <- ggbrain() + images(c(underlay = t1, signed_pe = signed_pe, abspe = abspe)) + slices(c("x = 25%", "x = 75%")) + define(c(signed_gt_abs = "signed_pe - abspe")) + geom_brain("signed_gt_abs") # contrast definitions can also occur inline, yielding equivalent plots gg_obj <- ggbrain() + images(c(underlay = t1, signed_pe = signed_pe, abspe = abspe)) + slices(c("x = 25%", "x = 75%")) + geom_brain("signed_pe - abspe") # The use of contrasts() is helpful when layers modify the contrast (e.g., subsetting) gg_obj <- ggbrain() + images(c(underlay = t1, signed_pe = signed_pe, abspe = abspe)) + slices(c("x = 25%", "x = 75%")) + define(c(signed_gt_abs = "signed_pe - abspe")) + geom_brain( "signed_gt_abs[signed_gt_abs > 0]", fill_scale=ggplot2::scale_fill_distiller("Pos diff", palette = "Reds") )
This function finds holes by flood filling TRUE into a 2D binary image, starting from the edge
im |
A boolean matrix representing a binary image |
nedges |
An integer specifying how many starting points along the edge to use for filling TRUE. The starts are northwest (1), southwest (2), southeast (3), and northeast (4). The compute time increases with the number of starts. |
This is an internal function used by geom_outline to clean up outlines
A matrix of the same size as im containing the number of neighboring pixels
Michael Hallquist
This function finds 'threads' hanging off of the edges of blobs in an image, allowing the user to trim them
im |
A numeric matrix representing an image, with non-zero values representing pixels to display |
min_neighbors |
the minimum number of neighbors a pixel must have to be retained |
maxit |
the maximum number of iterations to run the thread trimming algorithm. Default: 15. |
diagonal |
Whether to count diagonal elements as valid neighbors |
This algorithm runs count_neighbors iteratively until no pixel exceeds the trimming threshold min_neighbors
or the maximum number of iterations, maxit, is reached.
By running iteratively, long tails are trimmed sequentially by pruning the most disconnected voxels.
The algorithm computes neighbor counts once initially, then uses incremental updates when pixels are removed. This avoids redundant full-matrix scans on each iteration, providing significant speedup for large images.
A logical matrix matrix of the same size as im containing the number of neighboring pixels
Michael Hallquist
This function flood fills a binary image with TRUE for any value of FALSE
im |
A boolean matrix reference representing a binary image |
x |
the starting x position for fill |
y |
the starting y position for fill |
r |
the number of rows in im |
c |
the number of columns in im |
This is an internal function used by geom_outline to clean up outlines. Uses an iterative approach with an explicit stack to avoid stack overflow on large images.
Nothing. The matrix im is modified in place (by reference)
Michael Hallquist
Adds a raster layer to the ggbrain plot, displaying pixels from the specified layer definition
geom_brain( definition = NULL, name = NULL, fill = NULL, fill_scale = NULL, mapping = NULL, limits = NULL, breaks = NULL, show_legend = TRUE, interpolate = FALSE, unify_scales = TRUE, alpha = NULL, blur_edge = NULL, fill_holes = NULL, remove_specks = NULL, trim_threads = NULL )geom_brain( definition = NULL, name = NULL, fill = NULL, fill_scale = NULL, mapping = NULL, limits = NULL, breaks = NULL, show_legend = TRUE, interpolate = FALSE, unify_scales = TRUE, alpha = NULL, blur_edge = NULL, fill_holes = NULL, remove_specks = NULL, trim_threads = NULL )
definition |
a character string of the contrast or image definition used to define this layer.
Can be a simple image name (e.g., 'underlay') or a contrast string (e.g., |
name |
the name of this layer, used for referencing in layer and panel modifications |
fill |
A character string indicating the color used to fill all non-NA pixels in this layer. This is used to set
the fill color, in distinction to color mapping: |
fill_scale |
a ggplot scale_fill_* object used for mapping the fill column to the color of pixels in this layer. |
mapping |
the aesthetic mapping of the layer data to the display. Should be an aes() object and supports
|
limits |
if provided, sets the upper and lower bounds on the scale |
breaks |
if provided, a function to draw the breaks on the fill scale |
show_legend |
if TRUE, show the fill scale in the plot legend. Default is TRUE, except when 'name="underlay"“ |
interpolate |
passes to geom_raster and controls whether the fill is interpolated over continuous space |
unify_scales |
if TRUE, when this layer is reused across panels, unify the scales to match |
alpha |
a number between 0 and 1 that sets the alpha transparency of this layer. Default: 1 |
blur_edge |
the standard deviation (sigma) of a Gaussian kernel applied to the edge of this layer to smooth it. This makes the layer less jagged in appearance and is akin to antialiasing. |
fill_holes |
An optional positive integer specifying the size of holes (in pixels) inside clusters to be filled by nearest neighbor imputation. Default: 0. |
remove_specks |
An optional positive integer specifying the size of specks (in pixels) to be removed from each slice prior to display. Specks are small clusters that may be distracting and contribute to a 'salt and pepper' appearance. |
trim_threads |
the minimum number of neighboring pixels (including diagonals) that must be present to keep a pixel. |
Note that the fill_scale and limits must be specified at the time of the geom_brain creation in order for them to be mapped properly within ggplot. Because we overlay many raster layers in a ggplot object that all use the fill aesthetic mapping, it becomes hard to map the color scales after the layer is created using the typical + scale_fill_* syntax, and similarly for scale limits.
a ggb object populated with the relevant geom_brain and the action of 'add_layers'
# T1-weighted template t1 <- system.file("extdata", "mni_template_2009c_2mm.nii.gz", package = "ggbrain") # signed reward prediction error map signed_pe <- system.file("extdata", "pe_ptfce_fwep_0.05_2mm.nii.gz", package = "ggbrain") gg_obj <- ggbrain() + images(c(underlay = t1, overlay = signed_pe)) + slices(c("x = 25%", "x = 75%")) + geom_brain("underlay") + geom_brain(definition="overlay[overlay > 1]", fill_scale=ggplot2::scale_fill_viridis_c("pos z"))# T1-weighted template t1 <- system.file("extdata", "mni_template_2009c_2mm.nii.gz", package = "ggbrain") # signed reward prediction error map signed_pe <- system.file("extdata", "pe_ptfce_fwep_0.05_2mm.nii.gz", package = "ggbrain") gg_obj <- ggbrain() + images(c(underlay = t1, overlay = signed_pe)) + slices(c("x = 25%", "x = 75%")) + geom_brain("underlay") + geom_brain(definition="overlay[overlay > 1]", fill_scale=ggplot2::scale_fill_viridis_c("pos z"))
Clusterize a contrast/image and display clusters as categorical fill
geom_brain_clusterized( definition, name = NULL, nclusters = 10, min_clust_size = 1, nn = 3, fill_scale = NULL, show_legend = TRUE, cluster_info = c("number", "voxels"), blur_edge = NULL, fill_holes = NULL, remove_specks = NULL, trim_threads = NULL, sided = c("bisided", "two_sided") )geom_brain_clusterized( definition, name = NULL, nclusters = 10, min_clust_size = 1, nn = 3, fill_scale = NULL, show_legend = TRUE, cluster_info = c("number", "voxels"), blur_edge = NULL, fill_holes = NULL, remove_specks = NULL, trim_threads = NULL, sided = c("bisided", "two_sided") )
definition |
a character string of the contrast or image definition to cluster (e.g., |
name |
the name of this layer, used for referencing in layer and panel modifications |
nclusters |
maximum number of clusters to retain (largest by size). Default: 10 |
min_clust_size |
minimum cluster size in voxels. Default: 1 |
nn |
Neighborhood connectivity for defining clusters (1 = 6-connectivity, 2 = 18, 3 = 26). Default: 3 |
fill_scale |
a ggplot2 discrete scale_fill_* object to use for mapping cluster ids. If NULL, an automatic palette is used. |
show_legend |
logical; whether to show the cluster legend. Default: TRUE |
cluster_info |
character vector indicating which fields to include in cluster labels for the legend. Supported values: "number" (cluster index), "voxels" (voxel count), "size" (mm^3 volume). Order is respected. |
blur_edge, fill_holes, remove_specks, trim_threads
|
optional image refinements passed to |
sided |
Sidedness for clustering thresholded images. |
This helper clusters the given definition, adds the labeled cluster image to the plot, and draws it with a categorical fill.
It does not select slices; combine with slices() separately.
a ggb object that adds the clusterized layer
Adds an outline layer to the ggbrain plot, displaying outlines from the non-missing pixels in the specified layer definition
geom_outline( definition = NULL, name = NULL, outline = NULL, outline_scale = NULL, mapping = ggplot2::aes(outline = NULL, fill = NULL), size = NULL, limits = NULL, breaks = integer_breaks(), show_legend = TRUE, interpolate = FALSE, unify_scales = TRUE, alpha = 1, blur_edge = NULL, fill_holes = NULL, remove_specks = NULL, trim_threads = NULL, dil_ero = 0L )geom_outline( definition = NULL, name = NULL, outline = NULL, outline_scale = NULL, mapping = ggplot2::aes(outline = NULL, fill = NULL), size = NULL, limits = NULL, breaks = integer_breaks(), show_legend = TRUE, interpolate = FALSE, unify_scales = TRUE, alpha = 1, blur_edge = NULL, fill_holes = NULL, remove_specks = NULL, trim_threads = NULL, dil_ero = 0L )
definition |
a character string of the contrast or image definition used to define this layer.
Can be a simple image name (e.g., 'underlay') or a contrast string (e.g., |
name |
the name of this layer, used for referencing in layer and panel modifications |
outline |
A character string indicating the color used to draw outlines in this layer. This is used to set
the outline color, in distinction to outline color mapping: |
outline_scale |
a ggplot scale_fill_* object used for mapping the fill column to the color of pixels in this layer. |
mapping |
the aesthetic mapping of the layer data to the display. Should be an aes() object and supports
|
size |
the size of outlines to be drawn in pixel units. Default: 1 |
limits |
if provided, sets the upper and lower bounds on the scale |
breaks |
if provided, a function to draw the breaks on the fill scale |
show_legend |
if TRUE, show the fill scale in the plot legend |
interpolate |
passes to geom_raster and controls whether the fill is interpolated over continuous space |
unify_scales |
if TRUE, when this layer is reused across panels, unify the scales to match |
alpha |
a number between 0 and 1 that sets the alpha transparency of this layer. Default: 1 |
blur_edge |
the standard deviation (sigma) of a Gaussian kernel applied to the edge of this layer to smooth it. This makes the layer less jagged in appearance and is akin to antialiasing. |
fill_holes |
An optional positive integer specifying the size of holes (in pixels) inside clusters to be filled by nearest neighbor imputation. Default: 0. |
remove_specks |
An optional positive integer specifying the size of specks (in pixels) to be removed from each slice prior to display. Specks are small clusters that may be distracting and contribute to a 'salt and pepper' appearance. |
trim_threads |
the minimum number of neighboring pixels (including diagonals) that must be present to keep a pixel. |
dil_ero |
the number of pixels to dilate (> 0) or erode (< 0) the outline for display purposes. Default: 0L |
Note that the fill_scale and limits must be specified at the time of the geom_brain creation in order for them to be mapped properly within ggplot. Because we overlay many raster layers in a ggplot object that all use the fill aesthetic mapping, it becomes hard to map the color scales after the layer is created using the typical + scale_fill_* syntax, and similarly for scale limits.
a ggb object populated with the geom_outline layer and the action of 'add_layers'
# T1-weighted template t1 <- system.file("extdata", "mni_template_2009c_2mm.nii.gz", package = "ggbrain") # signed reward prediction error map signed_pe <- system.file("extdata", "pe_ptfce_fwep_0.05_2mm.nii.gz", package = "ggbrain") gg_obj <- ggbrain() + images(c(underlay = t1, overlay = signed_pe)) + slices(c("x = 25%", "x = 75%")) + geom_brain("underlay") + geom_outline(definition="overlay[overlay > 2]", outline="cyan")# T1-weighted template t1 <- system.file("extdata", "mni_template_2009c_2mm.nii.gz", package = "ggbrain") # signed reward prediction error map signed_pe <- system.file("extdata", "pe_ptfce_fwep_0.05_2mm.nii.gz", package = "ggbrain") gg_obj <- ggbrain() + images(c(underlay = t1, overlay = signed_pe)) + slices(c("x = 25%", "x = 75%")) + geom_brain("underlay") + geom_outline(definition="overlay[overlay > 2]", outline="cyan")
Variant of geom_label used for plotting region labels on slices
geom_region_label(image, label_column = "label", min_px = 1L, ...)geom_region_label(image, label_column = "label", min_px = 1L, ...)
image |
The name of the image within the underlying ggbrain_slices object that contains the labeled data positions |
label_column |
The column name name for the labels to use within the slice data |
min_px |
The minimum number of pixels present on a slice that will result in a text label. Default: 1 |
... |
All other parameters passed through to geom_label |
a ggb object with the relevant ggbrain_label field and an action of "add_region_labels"
Variant of geom_label_repel used for plotting region labels on slices with separation from other labels
geom_region_label_repel(image, label_column = "label", min_px = 1L, ...)geom_region_label_repel(image, label_column = "label", min_px = 1L, ...)
image |
The name of the image within the underlying ggbrain_slices object that contains the labeled data positions |
label_column |
The column name name for the labels to use within the slice data |
min_px |
The minimum number of pixels present on a slice that will result in a text label. Default: 1 |
... |
All other parameters passed through to geom_label_repel |
a ggb object with the relevant ggbrain_label field and an action of "add_region_labels"
Variant of geom_text used for plotting region labels on slices
geom_region_text(image, label_column = "label", min_px = 1L, ...)geom_region_text(image, label_column = "label", min_px = 1L, ...)
image |
The name of the image within the underlying ggbrain_slices object that contains the labeled data positions |
label_column |
The column name name for the labels to use within the slice data |
min_px |
The minimum number of pixels present on a slice that will result in a text label. Default: 1 |
... |
All other parameters passed through to geom_text |
a ggb object with the relevant ggbrain_label field and an action of "add_region_labels"
Variant of geom_text_repel used for plotting region labels on slices with separation from other labels
geom_region_text_repel(image, label_column = "label", min_px = 1L, ...)geom_region_text_repel(image, label_column = "label", min_px = 1L, ...)
image |
The name of the image within the underlying ggbrain_slices object that contains the labeled data positions |
label_column |
The column name name for the labels to use within the slice data |
min_px |
The minimum number of pixels present on a slice that will result in a text label. Default: 1 |
... |
All other parameters passed through to geom_text_repel |
a ggb object with the relevant ggbrain_label field and an action of "add_region_labels"
create ggb container object for a given plot
ggbrain( images = NULL, slices = NULL, title = NULL, bg_color = "grey8", text_color = NULL, base_size = 14 )ggbrain( images = NULL, slices = NULL, title = NULL, bg_color = "grey8", text_color = NULL, base_size = 14 )
images |
a character vector or existing ggbrain_images object defining which images should be included in this plot |
slices |
a set of slices to be added to the plot |
title |
the overall title to be added to the plot |
bg_color |
The background color of the overall plot |
text_color |
The default text color of the overall plot (passes through to panels). If NULL,
a high-contrast color is chosen based on |
base_size |
The base size of fonts used in the plot (cf. |
a ggb object containing basic information for a ggbrain plot such as background color,
text color, and font size
R6 class for compiling images to render in ggplot
R6 class for compiling images to render in ggplot
Note that this class is exported only for power users and rarely needs to be called directly in typical use of the package. Instead, look at images().
a ggbrain_images R6 class containing fields related to a set of NIfTI images imported into R
zero_tolthe (positive) numeric value that should be treated as indistinguishable from zero. This value is used to set small values in the images to exactly zero for proper masking. Default 1e-6
slicesa character vector of cached slice specifications to be used in $get_slices()
contrastsa character vector of cached contrast specifications to be used in $get_slices()
new()
create ggbrain_images object consisting of one or more NIfTI images
ggbrain_images$new(images = NULL, volumes = NULL, labels = NULL, filter = NULL)
imagesa character vector of file names containing NIfTI images to read
volumesthe volumes to be read from each element of images. By default, this is 1, in which case the first volume is
used, which is appropriate for all 3-D images. For 4-D images, volumes gives you more flexibility over the volume to display.
labelsA named list of data.frames with labels that map to values in the integer-valued/atlas elements of images. If
a single data.frame is passed, it will be accepted if only a single image is passed, too. These are then assumed to correspond
filterA named list of filter expressions to be applied to particular images. The names of the list correspond to the names
of the images provided. Each element of the list can either be a character vector denoting a filtering expression
(e.g., 'value < 100') or a numeric vector denoting values of the image that should be retained (e.g., c(5, 10, 12)).
add()
method to add another ggbrain_images object to this one
ggbrain_images$add(obj)
objthe ggbrain_images object to combine with this one
add_labels()
add a labels data.frame that connects an integer-valued image with a set of labels
ggbrain_images$add_labels(...)
...named arguments containing data.frame objects for each image to be labeled. The argument name should
match the image name to be labeled and the value should be a data.frame containing value and label.
As a result of $add_labels, the $get_slices method will always remap the numeric values for label images to the corresponding text-based labels in the label data. In addition, a new attribute will be returned called "slice_labels" that contains a row for each region represented in each slice.
add_images()
add one or more images to this ggbrain_images object
ggbrain_images$add_images(images = NULL, volumes = NULL)
imagesa character vector of file names containing NIfTI images to read
volumesa number indicating the volume within the images to read. At present, this must
be a single number – perhaps in the future, it could be a vector so that many timepoints in a 4-D image could
be displayed.
add_array_as_image()
add an in-memory array as a new image
ggbrain_images$add_array_as_image(arr, name, reference = NULL)
arrA 3D array to add as an image
nameThe name for this image
referenceOptional reference NIfTI image for header information. If NULL, uses the first existing image in the object as reference.
This is useful for adding computed/derived images (like cluster masks) without writing to disk. The array dimensions must match existing images.
filter_images()
filters an image based on an expression such as a subsetting operation
ggbrain_images$filter_images(filter = NULL)
filtera character string or numeric vector of the filter to apply
if expr is a numeric vector, only values in this set will be retained. If a character
string expression is used, it should use the variable name 'value' to refer to the numeric
values to be filtered, such as 'value > 10'.
dim()
return the 3D dimensions of the images contained in this object
ggbrain_images$dim()
get_image_names()
return the names of the images contained in this object
ggbrain_images$get_image_names()
get_images()
return the RNifti objects of one or more images contained in this object
ggbrain_images$get_images(img_names = NULL, drop = TRUE)
img_namesThe names of images to return. Use $get_image_names() if you're uncertain
about what is available.
dropIf TRUE, a single image is returned as an RNifti object, rather than a single-element list containing that object.
get_headers()
return the NIfTI headers for one or more images contained in this object
ggbrain_images$get_headers(img_names = NULL, drop = TRUE)
img_namesThe names of images whose header are returned. Use $get_image_names() if you're uncertain
about what is available.
dropIf TRUE, a single header is returned as an niftiHeader object, rather than a single-element list containing that object.
remove_images()
method for removing one or more images from the ggbrain_images object
ggbrain_images$remove_images(img_names)
img_namesnames of images to remove from object
winsorize_images()
winsorize the tails of a set of images to pull in extreme values
ggbrain_images$winsorize_images(img_names, quantiles = c(0.001, 0.999))
img_namesThe names of images in the ggbrain_images object to be winsorized
quantilesThe lower and upper quantiles used to define the thresholds for winsorizing.
na_images()
method to set values less than threshold to NA
ggbrain_images$na_images(img_names, threshold = NULL)
img_namesThe names of images in the ggbrain_images object whose values should be set to NA
thresholdThe threshold value whose absolute value used to determine which voxels to set to NA.
If NULL, use the pvt_zero_tol field (default 1e-6).
summary()
print a summary of the ggbrain_images object
ggbrain_images$summary()
get_nz_indices()
return the indices of non-zero voxels
ggbrain_images$get_nz_indices(img_names = NULL)
img_namesThe names of images in the ggbrain_images object whose non-zero indices should be looked up
Note that this function looks for non-zero voxels in any of the images specified by img_names.
add_slices()
adds one or more slices to the cached slices that will be retrieved by
$get_slices() when no slices argument is passed.
ggbrain_images$add_slices(slices = NULL)
slicesa character vector containing one or more slices to be extracted by $get_slices.
Uses the syntax "<xyz>=<number>". Example: c("x=10", "y=50%")
add_contrasts()
adds one or more contrasts to the cached contrasts that will be retrieved by
$get_slices() when no contrasts argument is passed.
ggbrain_images$add_contrasts(contrasts = NULL)
contrastsa character vector containing one or more contrasts to be extracted by $get_slices.
Uses the syntax "<img_name>[subset_expression] + <img_name>".
reset_slices()
remove all cached slice settings
ggbrain_images$reset_slices()
get_slices()
get slice data for one or more slices based on their coordinates
ggbrain_images$get_slices( slices = NULL, img_names = NULL, contrasts = NULL, fill_labels = FALSE, make_square = TRUE, remove_null_space = TRUE, target_resolution = NULL, resample_interpolation = 5L )
slicesa vector of slice positions
img_namesa character vector of images contained in the ggbrain_images object to be sliced
contrastsa named character vector of contrasts to be calculated for each slice
fill_labelsif TRUE, the numeric value of the image will be used for any value that does not have a corresponding label in the labels data.frame. Default: FALSE
make_squareIf TRUE, make all images square and of the same size
remove_null_spaceIf TRUE, remove slices where all values are approximately zero
target_resolutionOptional target voxel size in mm for resampling slices. If provided, slices will be resampled to this resolution using the specified interpolation method.
resample_interpolationInteger specifying the interpolation method for imager::imresize. 1=nearest, 2=linear, 5=cubic (default), 6=lanczos.
This function always returns a data.frame where each row represents a slice requested by the user. The $slice_data element is a list-column where each element is itself a list of slice data for a given layer/image (e.g., underlay or overlay) . The $slice_matrix is a list-column where each element is a list of 2-D matrices, one per layer/image. @return a ggbrain_slices object containing the requested slices and contrasts
get_slices_inplane()
get_slices_inplane is mostly an internal funciton for getting one or more slices from a given plane
ggbrain_images$get_slices_inplane( imgs = NULL, slice_numbers, plane, drop = FALSE )
imgsThe names of images to slice
slice_numbersThe numbers of slices in the specified plant to grab
planeThe image plane to slice. Must be "coronal", "sagittal", or "axial"
dropif TRUE, a single slice is returned as a 2D matrix instead of a 3D matrix with a singleton first dimension
A 3D matrix of slices x dim1 x dim2
get_labels()
return a list of data.frames containing labels for a given image
ggbrain_images$get_labels()
the names of the list correspond directly with the names of the images
get_orientation_labels()
internal helper to determine anatomical orientation labels for the first image
ggbrain_images$get_orientation_labels()
a list with elements x, y, z giving the orientation codes (e.g., c(\"L\", \"R\"))
lookup_slices()
internal function to lookup which slices to display along each axis based on their quantile, xyz coordinate, or ijk coordinate
ggbrain_images$lookup_slices(slices, ignore_null_space = TRUE)
slicesA character vector of coordinates for slices to display
ignore_null_spaceIf TRUE, any coordinates specified as quantiles (e.g., x = 50%) use the quantiles of only the non-zero slices (ignoring blank sliaces)
clone()
The objects of this class are cloneable with this method.
ggbrain_images$clone(deep = FALSE)
deepWhether to make a deep clone.
R6 class for adding labels to a ggbrain_panel
R6 class for adding labels to a ggbrain_panel
a ggbrain_label R6 class containing fields related to ggbrain plot labels
addl_argsa named list of additional argument to be passed to geom_text/geom_label at render
dataa data.frame containing labels to be printed on the panel. Must contain dim1, dim2, and label as columns. The dim1 and dim2 columns control where the labels will appear on the panel
imageA character string specifying the image to which these labels pertain
label_columnA character string indicating which data.frame column should be used for drawing labels
min_pxA positive integer indicating the minimum number of pixels present on slice that will generate a label
new()
create a new ggbrain_label object
ggbrain_label$new( data = NULL, geom = "text", image = NULL, label_column = NULL, min_px = NULL, ... )
dataa data.frame containing labels to be printed on the panel. Must contain dim1, dim2, and label as columns. The dim1 and dim2 columns control where the labels will appear on the panel
geomThe geom type to be plotted. Must be "text" or "label", corresponding to geom_text and geom_label, respectively.
imageA string specifying the image to which these labels pertain
label_columnthe column in data that should be drawn as labels on the plot
min_pxthe minimum number of pixels on a slice required to display label. Default: 1
...All other arguments that will be passed directly to geom_text or geom_label such as hjust, size, and color
add_to_gg()
add this text layer to an existing ggplot object
ggbrain_label$add_to_gg(base_gg)
base_ggthe ggplot object to which we add the layer
clone()
The objects of this class are cloneable with this method.
ggbrain_label$clone(deep = FALSE)
deepWhether to make a deep clone.
R6 class for a single layer of a ggbrain panel
R6 class for a single layer of a ggbrain panel
Note that this class is exported only for power users and rarely needs to be called directly in typical use of the package. Instead, look at geom_brain() and geom_outline().
a ggbrain_layer R6 class containing fields related to a visual layer on the ggbrain plot
namethe name of this layer, used for referencing in layer and panel modifications
all_nawhether all values for this layer are NA in the data field
definitiona character string specifying the image name or contrast that defines this layer
sourcea character string specifying the layer source within a relevant ggbrain_slices object. This is used to lookup the right layer information when combining slices and layers together Note that multiple layers can potentially have the same source, which is why a 1:1 mapping to name does not work
datathe data.frame containing relevant data for this layer.
show_legenda logical indicating whether to show or hide the fill/color scale
unify_scalesa logical indicating whether to unify scale limits and levels when this layer is added across many panels
bisidedread-only access to whether this layer uses a bisided color scale
categorical_fillread-only access to whether this layer has a categorical fill scale
fill_columnread-only access to layer fill column
fill_scalea scale_fill_* object containing the ggplot2 fill scale for this layer
alphasets the alpha transparency of this layer.
blur_edgecontrols the standard deviation (sigma) of a Gaussian blur applied to the layer at the edge
trim_threadsiteratively trim any pixels that have fewer than this number of neighboring pixels
fill_holescontrols the size of holes to be filled for display (in pixels)
remove_speckscontrols the size of specks to be removed (in pixels)
new()
create a new ggbrain_layer object
ggbrain_layer$new( name = NULL, definition = NULL, limits = NULL, breaks = integer_breaks(), show_legend = TRUE, interpolate = NULL, unify_scales = TRUE, alpha = NULL, blur_edge = NULL, fill_holes = NULL, remove_specks = NULL, trim_threads = NULL, data = NULL )
namethe name of this layer, used for referencing in layer and panel modifications
definitionan optional character string defining the image or contrast that should be used to lookup data from a ggbrain_slices object. This is mostly used internally by the ggbrain + syntax to allow layers to be defined without data in advance of the plot.
limitsif provided, sets the upper and lower bounds on the scale
breaksif provided, a function to draw the breaks on the color scale
show_legendif TRUE, show the scale on the plot legend
interpolatepasses to geom_raster and controls whether the fill is interpolated over continuous space
unify_scalesif TRUE, when this layer is reused across panels, unify the scales to match
alphafixed alpha transparency of this layer (use mapping for alpha mapping')
blur_edgethe standard deviation (sigma) of a Gaussian kernel applied to the edge of this layer to smooth it. This makes the layer less jagged in appearance and is akin to antialiasing.
fill_holesthe size of holes (in pixels) inside clusters to be filled by nearest neighbor imputation prior to display
remove_specksthe size of specks (in pixels) to be removed from each slice prior to display
trim_threadsthe minimum number of neighboring pixels (including diagonals) that must be present to keep a pixel
datathe data.frame containing image data for this layer. Must contain "dim1", "dim2", and "value" as columns
set_limits()
set the limits for this layer's scale
ggbrain_layer$set_limits(limits)
limitsa 2-element numeric vector setting the lower and upper limits on the layer's scale
set_pos_limits()
set the limits for this layer's positive scale (only relevant to bisided)
ggbrain_layer$set_pos_limits(limits)
limitsa 2-element numeric vector setting the lower and upper limits on the layer's positive scale
set_neg_limits()
set the limits for this layer's positive scale (only relevant to bisided)
ggbrain_layer$set_neg_limits(limits)
limitsa 2-element numeric vector setting the lower and upper limits on the layer's positive scale
set_breaks()
set the breaks element of this layer's scale
ggbrain_layer$set_breaks(breaks)
breaksa function used to label the breaks
set_pos_breaks()
set the breaks element of this layer's positive scale (only relevant to bisided)
ggbrain_layer$set_pos_breaks(breaks)
breaksa function used to label the positive breaks
set_neg_breaks()
set the breaks element of this layer's negative scale (only relevant to bisided)
ggbrain_layer$set_neg_breaks(breaks)
breaksa function used to label the negative breaks
plot()
plot this layer alone (mostly for debugging)
ggbrain_layer$plot()
add_to_gg()
method to add this layer to an existing ggplot object
ggbrain_layer$add_to_gg(base_gg)
base_ggthe ggplot object to which we add the layer
get_data()
return the data.frame associated with this layer
ggbrain_layer$get_data(add_layer_name = FALSE)
add_layer_nameif TRUE, adds a layer_name column to the data.frame for record-keeping.
Default: FALSE.
is_empty()
returns TRUE if all values are NA or if the data has 0 rows
ggbrain_layer$is_empty()
clone()
The objects of this class are cloneable with this method.
ggbrain_layer$clone(deep = FALSE)
deepWhether to make a deep clone.
R6 class for a single layer of a ggbrain panel using fill geom
R6 class for a single layer of a ggbrain panel using fill geom
Note that this class is exported only for power users and rarely needs to be called directly
in typical use of the package. Instead, look at geom_brain().
a ggbrain_layer_brain R6 class with fields related to a brain visual layer (relates to geom_brain)
ggbrain::ggbrain_layer -> ggbrain_layer_brain
fillcontrols color of the filled in pixels for non-NA (valid) voxels. Note that this
sets the fill color, while the mapping=aes(fill=<value>) would map the fill to a column
in the data, consistent with ggplot2 logic.
mappingthe ggplot2 aesthetic mapping between the data columns and the display
ggbrain::ggbrain_layer$add_to_gg()ggbrain::ggbrain_layer$get_data()ggbrain::ggbrain_layer$is_empty()ggbrain::ggbrain_layer$plot()ggbrain::ggbrain_layer$set_breaks()ggbrain::ggbrain_layer$set_limits()ggbrain::ggbrain_layer$set_neg_breaks()ggbrain::ggbrain_layer$set_neg_limits()ggbrain::ggbrain_layer$set_pos_breaks()ggbrain::ggbrain_layer$set_pos_limits()new()
create a new ggbrain_layer object
ggbrain_layer_brain$new( name = NULL, definition = NULL, limits = NULL, breaks = integer_breaks(), show_legend = TRUE, interpolate = NULL, unify_scales = TRUE, alpha = NULL, mapping = ggplot2::aes(fill = value), fill = NULL, fill_scale = NULL, blur_edge = NULL, fill_holes = NULL, remove_specks = NULL, trim_threads = NULL, data = NULL )
namethe name of this layer, used for referencing in layer and panel modifications
definitionan optional character string defining the image or contrast that should be used to lookup data from a ggbrain_slices object. This is mostly used internally by the ggbrain + syntax to allow layers to be defined without data in advance of the plot.
limitsif provided, sets the upper and lower bounds on the scale
breaksif provided, a function to draw the breaks on the color scale
show_legendif TRUE, show the scale on the plot legend
interpolatepasses to geom_raster and controls whether the fill is interpolated over continuous space
unify_scalesif TRUE, when this layer is reused across panels, unify the scales to match
alphaa number between 0 and 1 that sets the alpha transparency of this layer. Default: 1
mappingthe aesthetic mapping of the layer data to the display. Should be an aes() object and supports
fill (color of filled pixels). Default is aes(fill=value), which maps the numeric value of the layer data
to the fill color of the squares at each spatial position. For labeled data, you might use aes(fill=<label_col_name>).
fillA character string indicating the color used to fill all non-NA pixels in this layer. This is used in
distinction to mapping=aes(fill=<variable>).
fill_scalea ggplot scale object used for mapping the value column as the fill color for the layer.
blur_edgethe standard deviation (sigma) of a Gaussian kernel applied to the edge of this layer to smooth it. This makes the layer less jagged in appearance and is akin to antialiasing.
fill_holesthe size of holes (in pixels) inside clusters to be filled by nearest neighbor imputation prior to display
remove_specksthe size of specks (in pixels) to be removed from each slice prior to display
trim_threadsthe minimum number of neighboring pixels (including diagonals) that must be present to keep a pixel
datathe data.frame containing image data for this layer. Must contain "dim1", "dim2", and "value" as columns
To set mapping, you must provide a ggplot2 aes() object. A geom_brain() layer requires
a fill aesthetic mapping, which controls the fill color of regions.
clone()
The objects of this class are cloneable with this method.
ggbrain_layer_brain$clone(deep = FALSE)
deepWhether to make a deep clone.
R6 class for a single layer of a ggbrain panel using outline geom
R6 class for a single layer of a ggbrain panel using outline geom
Note that this class is exported only for power users and rarely needs to be called directly
in typical use of the package. Instead, look at geom_outline().
a ggbrain_layer_outline R6 class with fields related to a brain visual layer (relates to geom_outline)
ggbrain::ggbrain_layer -> ggbrain_layer_outline
mappingthe ggplot2 aesthetic mapping between the data columns and the display
outlinecontrols color of outline draw around non-NA (valid) voxels
outline_scalea scale_fill_* object containing the ggplot2 outline color scale for this layer
sizecontrols size of outline drawn around non-NA (valid) voxels
dil_erocontrols the number of pixels to dilate (> 0) or erode (< 0) the outline
ggbrain::ggbrain_layer$add_to_gg()ggbrain::ggbrain_layer$get_data()ggbrain::ggbrain_layer$is_empty()ggbrain::ggbrain_layer$plot()ggbrain::ggbrain_layer$set_breaks()ggbrain::ggbrain_layer$set_limits()ggbrain::ggbrain_layer$set_neg_breaks()ggbrain::ggbrain_layer$set_neg_limits()ggbrain::ggbrain_layer$set_pos_breaks()ggbrain::ggbrain_layer$set_pos_limits()new()
create a new ggbrain_layer object
ggbrain_layer_outline$new( name = NULL, definition = NULL, limits = NULL, breaks = integer_breaks(), show_legend = TRUE, interpolate = NULL, unify_scales = TRUE, alpha = NULL, mapping = ggplot2::aes(outline = NULL, fill = NULL), outline = NULL, outline_scale = NULL, size = NULL, blur_edge = NULL, fill_holes = NULL, remove_specks = NULL, trim_threads = NULL, dil_ero = NULL, data = NULL )
namethe name of this layer, used for referencing in layer and panel modifications
definitionan optional character string defining the image or contrast that should be used to lookup data from a ggbrain_slices object. This is mostly used internally by the ggbrain + syntax to allow layers to be defined without data in advance of the plot.
limitsif provided, sets the upper and lower bounds on the scale
breaksif provided, a function to draw the breaks on the color scale
show_legendif TRUE, show the scale on the plot legend
interpolatepasses to geom_raster and controls whether the fill is interpolated over continuous space
unify_scalesif TRUE, when this layer is reused across panels, unify the scales to match
alphaa number between 0 and 1 that sets the alpha transparency of this layer. Default: 1
mappingthe aesthetic mapping of the layer data to the display. Should be an aes() object and supports
outline (color of outline around clusters). Default is aes(outline=value), which maps the numeric value of the layer data
to the outline color of the squares at around spatial regions. For labeled data, you might use aes(fill=<label_col_name>).
outlineA character string indicating the color used to outline all non-NA pixels in this layer. This is used in
distinction to mapping=aes(outline=<variable>).
outline_scalea ggplot scale object used for mapping the value column as the outline color for the layer.
sizecontrols the thickness of outlines
blur_edgethe standard deviation (sigma) of a Gaussian kernel applied to the edge of this layer to smooth it. This makes the layer less jagged in appearance and is akin to antialiasing.
fill_holesthe size of holes (in pixels) inside clusters to be filled by nearest neighbor imputation prior to display
remove_specksthe size of specks (in pixels) to be removed from each slice prior to display
trim_threadsthe minimum number of neighboring pixels (including diagonals) that must be present to keep a pixel
dil_erothe number of pixels to dilate (> 0) or erode (<0) the outline.
datathe data.frame containing image data for this layer. Must contain "dim1", "dim2", and "value" as columns
To set mapping, you must provide a ggplot2 aes() object. A geom_outline() layer requires
an outline aesthetic mapping, which controls the color of outlines drawn around regions.
note that the ggbrain_layer_outline class maps onto *_fill fields
clone()
The objects of this class are cloneable with this method.
ggbrain_layer_outline$clone(deep = FALSE)
deepWhether to make a deep clone.
R6 class for a single panel of a ggbrain image
R6 class for a single panel of a ggbrain image
Note that this class is exported only for power users and rarely needs to be called directly
in typical use of the package. Instead, look at slices().
a ggbrain_panel R6 class with fields related to a panel on the ggbrain plot
ggThe ggplot object that contains the panel
new()
create a new ggbrain_panel object
ggbrain_panel$new( layers = NULL, title = NULL, bg_color = NULL, text_color = NULL, border_color = NULL, border_size = NULL, xlab = NULL, ylab = NULL, theme_custom = NULL, annotations = NULL, region_labels = NULL )
layersa list of ggbrain_layer objects to form the panel
titlea title for the panel added to the ggplot object using ggtitle()
bg_colorthe color used for the background of the plot. Default: 'gray10' (nearly black)
text_colorthe color used for text displayed on the plot. If NULL (default), a contrasting color is chosen based on the panel background.
border_colorthe color used for drawing a border around on the plot. Default: 'gray50' (though borders are not drawn by default).
border_sizethe size of the border line drawn around the panel. Default: NULL. If this value is
greater than zero, a border of this size and with color border_color will be drawn around the panel
xlabThe label to place on x axis. Default is NULL.
ylabThe label to place on y axis. Default is NULL.
theme_customAny custom theme() settings to be added to the plot
annotationsa data.frame containing all annotations to be added to this plot. Each row is cleaned up and passed to ggplot2::annotate()
region_labelsa list of ggbrain_label objects with data for plotting region labels on this panel
reset_limits()
Reset the scale limits for the specified layers
ggbrain_panel$reset_limits(layer_names)
layer_namesnot implemented yet
plot()
plot the panel
ggbrain_panel$plot(use_global_limits = TRUE)
use_global_limitsNot implemented at present
add_to_gg()
add one or more custom ggplot settings to the panel
ggbrain_panel$add_to_gg(list_args)
list_argsA list containing elements to add to the ggplot object
Note that passing in an expression such as theme_bw() + ggtitle("hello") will not work because it creates an object that cannot be added sequentially to the ggplot. As noted in ggplot2's documentation (https://ggplot2.tidyverse.org/reference/gg-add.html), to programmatically add elements to a ggplot, pass in a list where each element is added sequentially
add_layer()
adds a ggplot_layer object to the panel
ggbrain_panel$add_layer(layer_obj)
layer_obja ggbrain_layer object to add to the panel
remove_layers()
removes one or more layers by name
ggbrain_panel$remove_layers(layer_names)
layer_namesa character string of the layers to remove from the panel
get_data()
returns the data for all layers in the object
ggbrain_panel$get_data()
get_layer_names()
returns the names of the layers in this panel, ordered from bottom to top
ggbrain_panel$get_layer_names()
get_layers()
returns a list of ggbrain_layer objects that comprise this panel
ggbrain_panel$get_layers()
set_layer_order()
sets the order of layers from bottom to top based on the layer names provided
ggbrain_panel$set_layer_order(ordered_names = NULL)
ordered_namesthe names of the layers in the desired order from bottom to top. All layer names must be provided, not just a subset
clone()
The objects of this class are cloneable with this method.
ggbrain_panel$clone(deep = FALSE)
deepWhether to make a deep clone.
An R6 class for constructing a ggbrain plot from a ggbrain_slices object
An R6 class for constructing a ggbrain plot from a ggbrain_slices object
Note that this class is exported only for power users and rarely needs to be called directly
in typical use of the package. Instead, look at ggbrain().
a ggbrain_plot R6 class containing fields related to a ggbrain plot object
slicesa ggbrain_slices object containing all slice data for this plot
layersa list of ggbrain_layer objects for this plot. Note that in assignment, the
input can be a list of ggbrain_layer objects, or a list of lists where each inner element
specifies the settings for that layer. Example: list(list(name='hello', fill_scale=scale_fill_distiller())
annotationsa list of annotations to be added to this plot
region_labelsa list of region_labels to be added to this plot
panel_settingsa list of panel settings (aesthetics) to be added to this plot
titleoverall plot title, added to composite plot by patchwork::plot_annotation()
bg_colorbackground color of plot
text_colorthe color of text use across panels (can be overridden by panel settings)
base_sizethe base size of text used in ggplot theming
new()
instantiate a new instance of a ggbrain_plot object
ggbrain_plot$new( title = NULL, bg_color = NULL, text_color = NULL, base_size = NULL, slice_data = NULL )
titleoverall plot title
bg_colorbackground color of plot
text_colortext color of plot. If NULL, a contrasting color is chosen from the background.
base_sizebase size of text used in ggplot theming
slice_dataa ggbrain_slices object generated by ggbrain_images$get_slices()
add_layers()
adds one or more ggbrain_layer objects to this plot
ggbrain_plot$add_layers(layers = NULL)
layersa list of ggbrain_layer objects (can also be a list that just specifies names, definitions, etc.)
reset_layers()
removes all existing layers from this ggbrain_plot object
ggbrain_plot$reset_layers()
generate_plot()
generate the plot
ggbrain_plot$generate_plot(layers = NULL, slice_indices = NULL)
layersa list of layers to be displayed on each panel, the order of which yields the
bottom-to-to drawing order within ggplot2. Each element of layers should be a list
that follows the approximate structure of the ggbrain_layer class, minimally including
the layer name, which is used to lookup data of images or contrasts within the
slice_data object. If NULL, all layers in the slices object will be plotted. If only
a character string is passed, then those layers will be plotted with default scales.
slice_indicesAn optional subset of slice indices to display from the stored slice data
In addition to name, the elements of a layer can include
fill_scale a ggplot2 scale object for coloring the layer. Should be a scale_fill_* object.
limits the numeric limits to use for the color scale of this layer
breaks the scale breaks to use for the color scale of this layer
show_legend if FALSE, the color scale will not appear in the legend
plot()
return a plot of all panels as a patchwork object
ggbrain_plot$plot(guides = "collect", ...)
guidesPasses through to patchwork::plot_layout to control how legends are combined across plots. The default is "collect", which collects legends within a given nesting level (removes duplicates).
...additional arguments. Not used currently
clone()
The objects of this class are cloneable with this method.
ggbrain_plot$clone(deep = FALSE)
deepWhether to make a deep clone.
S3 method to support adding ggbrain_label objects to an existing ggplot object
## S3 method for class 'ggbrain_label' ggplot_add(object, plot, object_name, ...)## S3 method for class 'ggbrain_label' ggplot_add(object, plot, object_name, ...)
object |
the ggbrain_layer object to be added to an existing ggplot |
plot |
the ggplot object |
object_name |
not used, but required by ggplot_add |
... |
additional arguments, not currently used |
S3 method to support adding ggbrain_layer objects to an existing ggplot object
## S3 method for class 'ggbrain_layer' ggplot_add(object, plot, object_name, ...)## S3 method for class 'ggbrain_layer' ggplot_add(object, plot, object_name, ...)
object |
the ggbrain_layer object to be added to an existing ggplot |
plot |
the ggplot object |
object_name |
not used, but required by ggplot_add |
... |
additional arguments, not currently used |
S3 method to support adding ggbrain_layer objects to an existing ggplot object
## S3 method for class 'ggbrain_panel' ggplot_add(object, plot, object_name, ...)## S3 method for class 'ggbrain_panel' ggplot_add(object, plot, object_name, ...)
object |
the ggbrain_layer object to be added to an existing ggplot |
plot |
the ggplot object |
object_name |
not used, but required by ggplot_add |
... |
additional arguments, not currently used |
Add images to a ggbrain object
images(images = NULL, volumes = NULL, labels = NULL, filter = NULL)images(images = NULL, volumes = NULL, labels = NULL, filter = NULL)
images |
a character vector or ggbrain_images object containing NIfTI images to add to this plot |
volumes |
a number indicating the volume within the |
labels |
a data.frame or named list of data.frame objects corresponding to images that should be labeled.
You can only provide a data.frame if there is a single image being added. If multiple images are added, the names of
the |
filter |
a named list or character string specifying an expression of values to retain in the image, or a numeric vector of values to retain. Calls ggbrain_images$filter_image() |
a ggb object with the relevant images and an action of 'add_images'
t1 <- system.file("extdata", "mni_template_2009c_2mm.nii.gz", package = "ggbrain") gg_obj <- ggbrain() + images(c(underlay = t1))t1 <- system.file("extdata", "mni_template_2009c_2mm.nii.gz", package = "ggbrain") gg_obj <- ggbrain() + images(c(underlay = t1))
breaks function to encourage integer-valued breaks, based on input from pretty
integer_breaks(n = 5, ...)integer_breaks(n = 5, ...)
n |
number of breaks (default = 5) |
... |
Additional arguments passed to the pretty() function |
Code from here: https://joshuacook.netlify.app/post/integer-values-ggplot-axis/
a function for generating integer-valued breaks on a continuous scale
Convenience function to add many slices in a montage along one of the 3D planes
montage( plane = NULL, n = 12, min = 0.1, max = 0.9, min_coord = NULL, max_coord = NULL )montage( plane = NULL, n = 12, min = 0.1, max = 0.9, min_coord = NULL, max_coord = NULL )
plane |
a character string specifying the 3D plane: "sagittal", "axial", "coronal", "x", "y", or "z" |
n |
number of slices to add in this plane. Default: 12 |
min |
the lowest quantile to be included in the montage (between 0 and 1). Default: 0.1 |
max |
the highest quantile to be included in the montage (between 0 and 1). Default: 0.9 |
min_coord |
the lowest spatial position (in image coordinate space) to be included in the montage. |
max_coord |
the highest spatial position (in image coordinate space) to be included in the montage. |
This can be used with slices to make a quick montage, such as slices(montage("axial", 10).
Also note that use of standardized coordinates (in quantiles, using min and max) is mutually exclusive
with the the image coordinate specifications min_coord and max_coord.
a character string containing the slice positions along the requested axis
t1 <- system.file("extdata", "mni_template_2009c_2mm.nii.gz", package = "ggbrain") gg_obj <- ggbrain() + images(c(underlay = t1)) + slices(montage("sagittal", 15))t1 <- system.file("extdata", "mni_template_2009c_2mm.nii.gz", package = "ggbrain") gg_obj <- ggbrain() + images(c(underlay = t1)) + slices(montage("sagittal", 15))
Imputes missing values in a 2D matrix based on the nearest non-missing neighbors in a given radius
in_mat |
a 2D matrix to fill using nearest neighbors |
neighbors |
the number of closest non-NA neighboring values to return within |
radius |
the radius (in pixels) around each missing value to search for non-missing neighbors. Default is 8. |
aggfun |
the function used to aggregate the neighbors in imputation. Supports "mean", "median", and "mode." |
ignore_zeros |
if TRUE, then zero is not a valid imputation value (since these are not data in NIfTIs) |
The "mode" aggfun should only be used when the matrix in_mat can be converted to integers without loss
of information (i.e., the data are integerish values already).
A copy of the matrix with NA values imputed by their nearest neighbors
S3 method to allow for plot(x) syntax with ggbrain (ggb) objects
## S3 method for class 'ggb' plot(x, ...)## S3 method for class 'ggb' plot(x, ...)
x |
the |
... |
additional arguments passed to the plot method |
This will plot the ggbrain object to the current graphics device
NULL, invisibly
S3 method to allow for plot() syntax with ggbrain_panel objects
## S3 method for class 'ggbrain_panel' plot(x, ...)## S3 method for class 'ggbrain_panel' plot(x, ...)
x |
the |
... |
additional argument passed to the plot method |
S3 method to allow for plot() syntax with rendered ggbrain patchwork objects
default S3 method for ggbrain_patchwork objects (post-render)
## S3 method for class 'ggbrain_patchwork' plot(x, ...) ## S3 method for class 'ggbrain_patchwork' print(x, ...)## S3 method for class 'ggbrain_patchwork' plot(x, ...) ## S3 method for class 'ggbrain_patchwork' print(x, ...)
x |
the |
... |
additional arguments. Not currently used |
patchworkGrob object, invisibly
S3 method to allow for plot() syntax with ggbrain_panel objects
## S3 method for class 'ggbrain_plot' plot(x, ...)## S3 method for class 'ggbrain_plot' plot(x, ...)
x |
the |
... |
additional argument passed to the plot method |
breaks function for including min + max with labels, and a few unlabeled ticks in between
range_breaks(n = 3, digits = 2)range_breaks(n = 3, digits = 2)
n |
number of breaks added within the min-max range |
digits |
number of decimal places to display |
a function for generating breaks on a continuous scale with the min and max labeled
ggb object to ggplot/patchwork objectFunction to convert ggb object to ggplot/patchwork object
render(x, ...)render(x, ...)
x |
optional. A |
... |
additional arguments passed to the $render method of |
If no x argument is passed in, this function can be used in a ggbrain addition chain to render a plot
to a ggplot-friendly object before additional ggplot or patchwork calls are added such as theme().
Or if x is passed in as an argument, return the rendered plot as a ggbrain_patchwork object.
a ggbrain_patchwork object of the rendered ggbrain plot
t1 <- system.file("extdata", "mni_template_2009c_2mm.nii.gz", package = "ggbrain") # version where render is added to the object in a ggplot-style chain gg_obj <- ggbrain() + images(c(underlay = t1)) + slices(c("x = 25%", "x = 75%")) + geom_brain("underlay") + render() + # convert to ggplot-friendly object ggplot2::theme(text=ggplot2::element_text(family="Serif")) # version where a ggbrain object is created in one step, then rendered in another brain_obj <- ggbrain() + images(c(underlay = t1)) + slices(c("x = 25%", "x = 75%")) + geom_brain("underlay") gg_obj <- render(brain_obj) + patchwork::plot_annotation(title="Overall title")t1 <- system.file("extdata", "mni_template_2009c_2mm.nii.gz", package = "ggbrain") # version where render is added to the object in a ggplot-style chain gg_obj <- ggbrain() + images(c(underlay = t1)) + slices(c("x = 25%", "x = 75%")) + geom_brain("underlay") + render() + # convert to ggplot-friendly object ggplot2::theme(text=ggplot2::element_text(family="Serif")) # version where a ggbrain object is created in one step, then rendered in another brain_obj <- ggbrain() + images(c(underlay = t1)) + slices(c("x = 25%", "x = 75%")) + geom_brain("underlay") gg_obj <- render(brain_obj) + patchwork::plot_annotation(title="Overall title")
S3 method to allow for render(x) syntax with ggbrain (ggb) objects
## S3 method for class 'ggb' render(x, ...)## S3 method for class 'ggb' render(x, ...)
x |
the |
... |
additional arguments passed to the render method |
the ggbrain_patchwork object that can be handed off to patchwork and ggplot2 functions.
scale for plotting separate color gradients for positive and negative values
scale_fill_bisided( name = ggplot2::waiver(), neg_scale = scale_fill_distiller(palette = "Blues", direction = 1), pos_scale = scale_fill_distiller(palette = "Reds"), symmetric = TRUE )scale_fill_bisided( name = ggplot2::waiver(), neg_scale = scale_fill_distiller(palette = "Blues", direction = 1), pos_scale = scale_fill_distiller(palette = "Reds"), symmetric = TRUE )
name |
the scale name to be printed in the legend (above positive scale) |
neg_scale |
a scale_fill_* object used for negative values |
pos_scale |
a scale_fill_* object used for positive values |
symmetric |
if TRUE, the limits of the positive scale will equal the inverse limits of the negative scale. Said differently, this makes the positive and negative scales symmetric |
Note that this will absolutely not work as a general purpose ggplot2 scale! The positive/negative combination is achieved by adding two layers/geoms behind the scenes with different color scale.
a ggplot2 scale of type ScaleContinuous that includes negative and positive fill
scales internally in the $neg_scale and $pos_scale elements
Adds slices to the ggbrain plot, including additional panel aesthetics
slices( coordinates = NULL, title = NULL, bg_color = NULL, text_color = NULL, border_color = NULL, border_size = NULL, xlab = NULL, ylab = NULL, theme_custom = NULL )slices( coordinates = NULL, title = NULL, bg_color = NULL, text_color = NULL, border_color = NULL, border_size = NULL, xlab = NULL, ylab = NULL, theme_custom = NULL )
coordinates |
a character vector specifying the x, y, or z coordinates of the slices to be added.
Can also be a |
title |
a title for the slice panels added to the ggplot object using |
bg_color |
the color used for the background of the panels. Default: |
text_color |
the color used for text displayed on the panels. If NULL (default), the plot's text color is used; when the plot text color is automatic, it is chosen for contrast against the panel background. |
border_color |
the color used for drawing a border around on the panels. Default: |
border_size |
the size of the border line drawn around the panels. Default: NULL. If this value is
greater than zero, a border of this size and with color |
xlab |
The label to place on x axis. Default is NULL. |
ylab |
The label to place on y axis. Default is NULL. |
theme_custom |
Any custom theme() settings to be added to the panels. |
note that if you pass in multiple coordinates (as a vector), the title, bg_color, and other attributes
will be reused for all slices added by this operation. Thus, if you want to customize specific slices or groups of slices, use
multiple addition operations, as in slices(c('x=10', 'y=15'), bg_color='white') + slices(c('x=18', 'y=22'), bg_color='black').
You can also pass the result of cluster_slices() to automatically select slices based on
cluster centers of mass in a thresholded image.
a ggb object with the relevant slices and an action of 'add_slices'
t1 <- system.file("extdata", "mni_template_2009c_2mm.nii.gz", package = "ggbrain") gg_obj <- ggbrain() + images(c(underlay = t1)) + slices(c("x = 25%", "x = 75%"), border_color = "blue")t1 <- system.file("extdata", "mni_template_2009c_2mm.nii.gz", package = "ggbrain") gg_obj <- ggbrain() + images(c(underlay = t1)) + slices(c("x = 25%", "x = 75%"), border_color = "blue")
Set the target resolution for resampling slices in a ggbrain plot
target_resolution(voxel_size, interpolation = "cubic")target_resolution(voxel_size, interpolation = "cubic")
voxel_size |
A positive number specifying the target voxel size in millimeters (e.g., 1 for 1mm isotropic). The slices will be resampled to this resolution before display. If the input images have larger voxels (e.g., 2.5mm), they will be upsampled to the target resolution. If the input images have smaller voxels (e.g., 0.5mm), they will be downsampled. |
interpolation |
A character string specifying the interpolation method to use. Options are:
|
This function allows you to display brain images at a different resolution than their native voxel size.
For example, if your functional MRI data have 2.5mm voxels but you want to display them at 1mm resolution
for publication-quality figures, you can use target_resolution(1) to upsample.
Conversely, if you have high-resolution images (e.g., 0.5mm) that are slow to render or result in
very large file sizes, you can downsample them using target_resolution(2) to display at 2mm.
The resampling is performed on each 2D slice after extraction, which is more efficient than resampling the entire 3D volume. The interpolation is applied to all images in the plot. For labeled/categorical images, nearest neighbor interpolation is always used to preserve integer values.
Note that upsampling does not add information to the image – it simply provides a smoother visual representation. For the highest quality results with functional overlays on anatomical underlays, consider using a high-resolution anatomical template (e.g., 1mm) as your underlay.
A ggb object with the target resolution settings and an action of 'set_target_resolution'
t1 <- system.file("extdata", "mni_template_2009c_2mm.nii.gz", package = "ggbrain") overlay <- system.file("extdata", "pe_ptfce_fwep_0.05_2mm.nii.gz", package = "ggbrain") # Display 2mm images at 1mm resolution (upsampling) using cubic interpolation gg_obj <- ggbrain() + images(c(underlay = t1, overlay = overlay)) + slices(c("x = 0", "z = 20")) + target_resolution(1, interpolation = "cubic") + geom_brain("underlay") + geom_brain("overlay") # Downsample to 4mm for faster rendering or smaller file sizes gg_obj_small <- ggbrain() + images(c(underlay = t1)) + slices(c("x = 0", "z = 20")) + target_resolution(4, interpolation = "linear") + geom_brain("underlay")t1 <- system.file("extdata", "mni_template_2009c_2mm.nii.gz", package = "ggbrain") overlay <- system.file("extdata", "pe_ptfce_fwep_0.05_2mm.nii.gz", package = "ggbrain") # Display 2mm images at 1mm resolution (upsampling) using cubic interpolation gg_obj <- ggbrain() + images(c(underlay = t1, overlay = overlay)) + slices(c("x = 0", "z = 20")) + target_resolution(1, interpolation = "cubic") + geom_brain("underlay") + geom_brain("overlay") # Downsample to 4mm for faster rendering or smaller file sizes gg_obj_small <- ggbrain() + images(c(underlay = t1)) + slices(c("x = 0", "z = 20")) + target_resolution(4, interpolation = "linear") + geom_brain("underlay")