surfplot package
Submodules
surfplot.datasets module
Convenient data fetchers for tutorial examples
- surfplot.datasets.load_example_data(dataset='default_mode', join=False)[source]
Load example datasets for tutorials
Precomputed association maps for terms ‘default mode’ or ‘frontoparietal’ using Neurosynth. In brief, maps were downloaded from Neurosynth and projected to fsLR space using
neuromaps.transforms.mni152_to_fslr
. Then, their vertex arrays were saved.Default mode: https://www.neurosynth.org/analyses/terms/default%20mode/
Frontoparietal: https://www.neurosynth.org/analyses/terms/frontoparietal/
Yarkoni T, Poldrack RA, Nichols TE, Van Essen DC, Wager TD. 2011. Large-scale automated synthesis of human functional neuroimaging data. Nat Methods. 8:665–670.
- Parameters
dataset ({'default_mode', 'frontoparietal'}, optional) – Neurosynth association map. Default: ‘default_mode’
join (bool, optional) – Return data as a single concatenated array. Default: False, which returns left and right hemisphere arrays, respectively
- Returns
numpy.ndarray – Vertex array(s)
surfplot.plotting module
Main module containing the Plot class
- class surfplot.plotting.Plot(surf_lh=None, surf_rh=None, layout='grid', views=None, mirror_views=False, flip=False, size=(500, 400), zoom=1.5, background=(1, 1, 1), label_text=None, brightness=0.5)[source]
Bases:
object
Plot brain surfaces with data layers
- Parameters
surf_lh (str or os.PathLike or BSPolyData, optional) – Left and right hemisphere cortical surfaces, either as a file path to a valid surface file (e.g., .gii. .surf) or a pre-loaded surface from
brainspace.mesh.mesh_io.read_surface()
. At least one hemisphere must be provided. Default: Nonesurf_rh (str or os.PathLike or BSPolyData, optional) – Left and right hemisphere cortical surfaces, either as a file path to a valid surface file (e.g., .gii. .surf) or a pre-loaded surface from
brainspace.mesh.mesh_io.read_surface()
. At least one hemisphere must be provided. Default: Nonelayout ({'grid', 'column', 'row'}, optional) – Layout in which to plot brain surfaces. ‘row’ plots brains as a single row ordered from left-to-right hemispheres (if applicable), ‘column’ plots brains as a single column descending from left-to-right hemispheres (if applicable). ‘grid’ plots surfaces as a views-by-hemisphere (left-right) array; if only one hemipshere is provided, then ‘grid’ is equivalent to ‘row’. By default ‘grid’.
views ({'lateral', 'medial', 'dorsal', 'ventral', 'anterior',) – ‘posterior’}, str or list[str], optional Views to plot for each provided hemisphere. Views are plotted in in the order they are provided. If None, then lateral and medial views are plotted. Default: None
mirror_views (bool, optional) – Flip the order of the right hemisphere views for ‘row’ or ‘column’ layouts, such that they mirror the left hemisphere views. Ignored if surf_rh is None and layout is ‘grid’.
flip (bool, optional) – Flip the display order of left and right hemispheres in grid or row layouts, if applicable. Useful when showing only ‘anterior` or ‘inferior’ views. Default: False
size (tuple of int, optional) – The size of the space to plot surfaces, defined by (width, height). Note that this differs from figsize in Plot.build(), which determines the overall figure size for the matplotlib figure. Default: (500, 400)
zoom (int, optional) – Level of zoom to apply. Default: 1.5
background (tuple, optional) – Background color, default: (1, 1, 1)
label_text (dict[str, array-like], optional) – Brainspace label text for column/row. Possible keys are {‘left’, ‘right’, ‘top’, ‘bottom’}, which indicate the location. See brainspace.plotting.surface_plotting.plot_surf for more details Default: None.
brightness (float, optional) – Brightness of plain gray surface. 0 = black, 1 = white. Default: .5
- Raises
ValueError – Neither surf_lh or surf_rh are provided
- add_layer(data, cmap='viridis', alpha=1, color_range=None, as_outline=False, zero_transparent=True, cbar=True, cbar_label=None)[source]
Add plotting layer to surface(s)
- Parameters
data (str or os.PathLike, numpy.ndarray, dict, nibabel.gifti.gifti.GiftiImage, or nibabel.cifti2.cifti2.Cifti2Image) – Vertex data to plot on surfaces. Must be a valid file path of a GIFTI or CIFTI image, a loaded GIFTI or CIFTI image, a numpy array with length equal to the total number of vertices in the provided surfaces (e.g., 32k in left surface + 32k in right surface = 64k total), or a dictionary with ‘left’ and/or ‘right keys. If a numpy array, vertices are assumed to be in order of left-to-right, if applicable. If a dictionary, then values can be any of the possible types mentioned above, assuming that the vertices match the vertices of their respective surface.
cmap (matplotlib colormap name or object, optional) – Colormap to use for data, default: ‘viridis’
alpha (float, optional) – Colormap opacity (0 to 1). Default: 1
color_range (tuple[float, float], optional) – Minimum and maximum value for color map. If None, then the minimum and maximum values in data are used. Default: None
as_outline (bool, optional) – Plot only an outline of contiguous vertices with the same value. Useful if plotting regions of interests, atlases, or discretized data. Not recommended for continous data. Default: False
zero_transparent (bool, optional) – Set vertices with value of 0 to NaN, which will turn them transparent on the surface. Useful when value of 0 has no importance (e.g., thresholded data, an atlas). Default: True
cbar (bool, optional) – Show colorbar for layer, default: True
cbar_label (str, optional) – Label to include with colorbar if shown. Note that this is not required for the colorbar to be drawn. Default: None
- Raises
ValueError – data keys must be ‘left’ and/or ‘right’
TypeError – data is neither an instance of str or os.PathLike, numpy.ndarray, dict, nibabel.gifti.gifti.GiftiImage, or nibabel.cifti2.cifti2.Cifti2Image
- build(figsize=None, colorbar=True, cbar_kws=None, scale=(2, 2))[source]
Build matplotlib figure of surface plot
- Parameters
figsize (tuple, optional) – Overall figure size, specified by (width, height). Default: None, which will determine the figure size based on the size parameter.
colorbar (bool, optional) – Draw colorbars for each applicable layer, default: True
cbar_kws (dict, optional) – Keyword arguments for
_add_colorbar()
. Default: None, which will plot the default colorbar parameters.scale (tuple, optional) – Amount to scale the surface plot. Default: (2, 2), which is a good baseline for higher resolution plotting.
- Returns
matplotlib.pyplot.figure – Surface plot figure
- render(offscreen=True)[source]
Generate surface plot with all provided layers
- Parameters
offscreen (bool, optional) – Render offscreen. Default: True
- Returns
brainspace.plotting.base.Plotter – Surface plot
- show(embed_nb=False, interactive=True, transparent_bg=True, scale=(1, 1))[source]
View Brainspace vtk surface rendering
Notes
This only shows the plot created by brainspace.plotting.surface_plotting.plot_surf, and will not include colorbars created by
plot()
or any other matplotlib components.- Parameters
embed_nb (bool, optional) – Whether to embed figure in notebook. Only used if running in a notebook. Default: False
interactive (bool, optional) – Whether to enable interaction, default: True
scale (tuple, optional) – Amount to scale the surface plot, default: (1, 1)
- Returns
Ipython Image or vtk panel – Brainspace surface plot rendering
surfplot.surf module
Surface plotting functions.
NB: Code in this module is a copied subset from: https://github.com/MICA-MNI/BrainSpace/blob/master/brainspace/plotting/surface_plotting.py
Code has been modified (lines 30-31) just to accommodate extra orientations (‘anterior’, ‘posterior’).
- surfplot.surf.build_plotter(surfs, layout, array_name=None, view=None, color_bar=None, color_range=None, share=False, label_text=None, cmap='viridis', nan_color=(0, 0, 0, 1), zoom=1, background=(1, 1, 1), size=(400, 400), **kwargs)[source]
Build plotter arranged according to the layout.
- Parameters
surfs (dict[str, BSPolyData]) – Dictionary of surfaces.
layout (array-like, shape = (n_rows, n_cols)) – Array of surface keys in surfs. Specifies how window is arranged.
array_name (array-like, optional) – Names of point data array to plot for each layout entry. Use a tuple with multiple array names to plot multiple arrays (overlays) per layout entry. Default is None.
view (array-like, optional) – View for each each layout entry. Possible views are {‘lateral’, ‘medial’, ‘ventral’, ‘dorsal’}. If None, use default view. Default is None.
color_bar ({'left', 'right', 'top', 'bottom'} or None, optional) – Location where color bars are rendered. If None, color bars are not included. Default is None.
color_range ({'sym'}, tuple or sequence.) – Range for each array name. If ‘sym’, uses a symmetric range. Only used if array has positive and negative values. Default is None.
share ({'row', 'col', 'both'} or bool, optional) – If
share == 'row'
, point data for surfaces in the same row share same data range. Ifshare == 'col'
, the same but for columns. Ifshare == 'both'
, all data shares same range. If True, similar toshare == 'both'
. Default is False.label_text (dict[str, array-like], optional) – Label text for column/row. Possible keys are {‘left’, ‘right’, ‘top’, ‘bottom’}, which indicate the location. Default is None.
cmap (str or sequence of str, optional) – Color map name (from matplotlib) for each array name. Default is ‘viridis’.
nan_color (tuple) – Color for nan values. Default is (0, 0, 0, 1).
zoom (float or sequence of float, optional) – Zoom applied to the surfaces in each layout entry.
background (tuple) – Background color. Default is (1, 1, 1).
size (tuple, optional) – Window size. Default is (400, 400).
kwargs (keyword-valued args) –
Additional arguments passed to the renderers, actors, mapper, color_bar or plotter. Keywords starting with:
’renderer__’ are passed to the renderers.
’actor__’ are passed to the actors.
’mapper__’ are passed to the mappers.
’cb__’ are passed to color bar actors.
’text__’ are passed to color text actors.
The rest of keywords are passed to the plotter.
- Returns
plotter (Plotter) – An instance of Plotter.
See also
plot_surf()
,plot_hemispheres()
Notes
If sequences, shapes of array_name, view and zoom must be equal or broadcastable to the shape of layout. Renderer keywords must also be broadcastable to the shape of layout.
If sequences, shapes of cmap and cbar_range must be equal or broadcastable to the shape of array_name, including the number of array names per entry. Actor and mapper keywords must also be broadcastable to the shape of array_name.
- surfplot.surf.plot_surf(surfs, layout, array_name=None, view=None, color_bar=None, color_range=None, share=False, label_text=None, cmap='viridis', nan_color=(0, 0, 0, 1), zoom=1, background=(1, 1, 1), size=(400, 400), embed_nb=False, interactive=True, scale=(1, 1), transparent_bg=True, screenshot=False, filename=None, return_plotter=False, **kwargs)[source]
Plot surfaces arranged according to the layout.
- Parameters
surfs (dict[str, BSPolyData]) – Dictionary of surfaces.
layout (array-like, shape = (n_rows, n_cols)) – Array of surface keys in surfs. Specifies how window is arranged.
array_name (array-like, optional) – Names of point data array to plot for each layout entry. Use a tuple with multiple array names to plot multiple arrays (overlays) per layout entry. Default is None.
view (array-like, optional) – View for each each layout entry. Possible views are {‘lateral’, ‘medial’, ‘ventral’, ‘dorsal’}. If None, use default view. Default is None.
color_bar ({'left', 'right', 'top', 'bottom'} or None, optional) – Location where color bars are rendered. If None, color bars are not included. Default is None.
color_range ({'sym'}, tuple or sequence.) – Range for each array name. If ‘sym’, uses a symmetric range. Only used if array has positive and negative values. Default is None.
share ({'row', 'col', 'both'} or bool, optional) – If
share == 'row'
, point data for surfaces in the same row share same data range. Ifshare == 'col'
, the same but for columns. Ifshare == 'both'
, all data shares same range. If True, similar toshare == 'both'
. Default is False.label_text (dict[str, array-like], optional) – Label text for column/row. Possible keys are {‘left’, ‘right’, ‘top’, ‘bottom’}, which indicate the location. Default is None.
cmap (str or sequence of str, optional) – Color map name (from matplotlib) for each array name. Default is ‘viridis’.
nan_color (tuple) – Color for nan values. Default is (0, 0, 0, 1).
zoom (float or sequence of float, optional) – Zoom applied to the surfaces in each layout entry.
background (tuple) – Background color. Default is (1, 1, 1).
size (tuple, optional) – Window size. Default is (400, 400).
interactive (bool, optional) – Whether to enable interaction. Default is True.
embed_nb (bool, optional) – Whether to embed figure in notebook. Only used if running in a notebook. Default is False.
screenshot (bool, optional) – Take a screenshot instead of rendering. Default is False.
filename (str, optional) – Filename to save the screenshot. Default is None.
transparent_bg (bool, optional) – Whether to us a transparent background. Only used if
screenshot==True
. Default is False.scale (tuple, optional) – Scale (magnification). Only used if
screenshot==True
. Default is None.kwargs (keyword-valued args) –
Additional arguments passed to the renderers, actors, mapper or plotter. Keywords starting with:
’renderer__’ are passed to the renderers.
’actor__’ are passed to the actors.
’mapper__’ are passed to the mappers.
The rest of keywords are passed to the plotter.
- Returns
figure (Ipython Image or panel or None) – Figure to plot. None if using vtk for rendering (i.e.,
embed_nb == False
).
See also
build_plotter()
,plot_hemispheres()
Notes
If sequences, shapes of array_name, view and zoom must be equal or broadcastable to the shape of layout. Renderer keywords must also be broadcastable to the shape of layout.
If sequences, shapes of cmap and cbar_range must be equal or broadcastable to the shape of array_name, including the number of array names per entry. Actor and mapper keywords must also be broadcastable to the shape of array_name.
surfplot.utils module
Utility functions that streamline preparing vertex arrays for plotting
- surfplot.utils.add_fslr_medial_wall(data, split=False)[source]
Add medial wall to data in fsLR space
Data in 32k fs_LR space (e.g., Human Connectome Project data) often exclude the medial wall in their data arrays, which results in a total of 59412 vertices across hemispheres. This function adds back in the missing medial wall vertices to produce a data array with the full 64984 vertices, which is required for plotting with 32k density fsLR surfaces.
- Parameters
data (numpy.ndarray) – Surface vertices. Must have exactly 59412 or 64984 vertices. Note that if 64984 vertices are present, then the medial wall is already included. If so, then only hemisphere splitting will be performed, if applied.
split (bool) – Return left and right hemipsheres as separate arrays. Default: False
- Returns
numpy.ndarray – Vertices with medial wall included (64984 vertices total)
- Raises
ValueError – data has the incorrect number of vertices (59412 or 64984 only accepted)
- surfplot.utils.threshold(data, thresh, binarize=False, two_sided=True)[source]
Threshold vertex array
- Parameters
data (numpy.ndarray) – Vertex array
thresh (float) – Threshold value. All values below or equal to threshold are set 0.
binarize (bool, optional) – Set all values above threshold to 1. Default: False
two_sided (bool, optional) – Apply thresholding to both positive and negative values. Default: True
- Returns
numpy.ndarray – Thresholded data
Module contents
- class surfplot.Plot(surf_lh=None, surf_rh=None, layout='grid', views=None, mirror_views=False, flip=False, size=(500, 400), zoom=1.5, background=(1, 1, 1), label_text=None, brightness=0.5)[source]
Bases:
object
Plot brain surfaces with data layers
- Parameters
surf_lh (str or os.PathLike or BSPolyData, optional) – Left and right hemisphere cortical surfaces, either as a file path to a valid surface file (e.g., .gii. .surf) or a pre-loaded surface from
brainspace.mesh.mesh_io.read_surface()
. At least one hemisphere must be provided. Default: Nonesurf_rh (str or os.PathLike or BSPolyData, optional) – Left and right hemisphere cortical surfaces, either as a file path to a valid surface file (e.g., .gii. .surf) or a pre-loaded surface from
brainspace.mesh.mesh_io.read_surface()
. At least one hemisphere must be provided. Default: Nonelayout ({'grid', 'column', 'row'}, optional) – Layout in which to plot brain surfaces. ‘row’ plots brains as a single row ordered from left-to-right hemispheres (if applicable), ‘column’ plots brains as a single column descending from left-to-right hemispheres (if applicable). ‘grid’ plots surfaces as a views-by-hemisphere (left-right) array; if only one hemipshere is provided, then ‘grid’ is equivalent to ‘row’. By default ‘grid’.
views ({'lateral', 'medial', 'dorsal', 'ventral', 'anterior',) – ‘posterior’}, str or list[str], optional Views to plot for each provided hemisphere. Views are plotted in in the order they are provided. If None, then lateral and medial views are plotted. Default: None
mirror_views (bool, optional) – Flip the order of the right hemisphere views for ‘row’ or ‘column’ layouts, such that they mirror the left hemisphere views. Ignored if surf_rh is None and layout is ‘grid’.
flip (bool, optional) – Flip the display order of left and right hemispheres in grid or row layouts, if applicable. Useful when showing only ‘anterior` or ‘inferior’ views. Default: False
size (tuple of int, optional) – The size of the space to plot surfaces, defined by (width, height). Note that this differs from figsize in Plot.build(), which determines the overall figure size for the matplotlib figure. Default: (500, 400)
zoom (int, optional) – Level of zoom to apply. Default: 1.5
background (tuple, optional) – Background color, default: (1, 1, 1)
label_text (dict[str, array-like], optional) – Brainspace label text for column/row. Possible keys are {‘left’, ‘right’, ‘top’, ‘bottom’}, which indicate the location. See brainspace.plotting.surface_plotting.plot_surf for more details Default: None.
brightness (float, optional) – Brightness of plain gray surface. 0 = black, 1 = white. Default: .5
- Raises
ValueError – Neither surf_lh or surf_rh are provided
- add_layer(data, cmap='viridis', alpha=1, color_range=None, as_outline=False, zero_transparent=True, cbar=True, cbar_label=None)[source]
Add plotting layer to surface(s)
- Parameters
data (str or os.PathLike, numpy.ndarray, dict, nibabel.gifti.gifti.GiftiImage, or nibabel.cifti2.cifti2.Cifti2Image) – Vertex data to plot on surfaces. Must be a valid file path of a GIFTI or CIFTI image, a loaded GIFTI or CIFTI image, a numpy array with length equal to the total number of vertices in the provided surfaces (e.g., 32k in left surface + 32k in right surface = 64k total), or a dictionary with ‘left’ and/or ‘right keys. If a numpy array, vertices are assumed to be in order of left-to-right, if applicable. If a dictionary, then values can be any of the possible types mentioned above, assuming that the vertices match the vertices of their respective surface.
cmap (matplotlib colormap name or object, optional) – Colormap to use for data, default: ‘viridis’
alpha (float, optional) – Colormap opacity (0 to 1). Default: 1
color_range (tuple[float, float], optional) – Minimum and maximum value for color map. If None, then the minimum and maximum values in data are used. Default: None
as_outline (bool, optional) – Plot only an outline of contiguous vertices with the same value. Useful if plotting regions of interests, atlases, or discretized data. Not recommended for continous data. Default: False
zero_transparent (bool, optional) – Set vertices with value of 0 to NaN, which will turn them transparent on the surface. Useful when value of 0 has no importance (e.g., thresholded data, an atlas). Default: True
cbar (bool, optional) – Show colorbar for layer, default: True
cbar_label (str, optional) – Label to include with colorbar if shown. Note that this is not required for the colorbar to be drawn. Default: None
- Raises
ValueError – data keys must be ‘left’ and/or ‘right’
TypeError – data is neither an instance of str or os.PathLike, numpy.ndarray, dict, nibabel.gifti.gifti.GiftiImage, or nibabel.cifti2.cifti2.Cifti2Image
- build(figsize=None, colorbar=True, cbar_kws=None, scale=(2, 2))[source]
Build matplotlib figure of surface plot
- Parameters
figsize (tuple, optional) – Overall figure size, specified by (width, height). Default: None, which will determine the figure size based on the size parameter.
colorbar (bool, optional) – Draw colorbars for each applicable layer, default: True
cbar_kws (dict, optional) – Keyword arguments for
_add_colorbar()
. Default: None, which will plot the default colorbar parameters.scale (tuple, optional) – Amount to scale the surface plot. Default: (2, 2), which is a good baseline for higher resolution plotting.
- Returns
matplotlib.pyplot.figure – Surface plot figure
- render(offscreen=True)[source]
Generate surface plot with all provided layers
- Parameters
offscreen (bool, optional) – Render offscreen. Default: True
- Returns
brainspace.plotting.base.Plotter – Surface plot
- show(embed_nb=False, interactive=True, transparent_bg=True, scale=(1, 1))[source]
View Brainspace vtk surface rendering
Notes
This only shows the plot created by brainspace.plotting.surface_plotting.plot_surf, and will not include colorbars created by
plot()
or any other matplotlib components.- Parameters
embed_nb (bool, optional) – Whether to embed figure in notebook. Only used if running in a notebook. Default: False
interactive (bool, optional) – Whether to enable interaction, default: True
scale (tuple, optional) – Amount to scale the surface plot, default: (1, 1)
- Returns
Ipython Image or vtk panel – Brainspace surface plot rendering