### Install surfplot from GitHub Source: https://surfplot.readthedocs.io/en/latest/installation.html Clone the surfplot repository from GitHub and install it locally. This method installs the latest development version. ```bash git clone https://github.com/danjgale/surfplot.git cd surfplot pip install . ``` -------------------------------- ### Load Example Data and Verify Length Source: https://surfplot.readthedocs.io/en/latest/auto_examples/plot_tutorial_03.html Loads example data and verifies that its length matches the combined vertex count of both hemispheres. ```python # return a single concatenated array from both hemispheres data = load_example_data(join=True) print(len(data) == 64984) ``` -------------------------------- ### Install neuromaps Source: https://surfplot.readthedocs.io/en/latest/auto_examples/index.html Install the neuromaps library using pip. This is often required for tutorials and examples that automatically download surface data. ```bash pip install neuromaps ``` -------------------------------- ### surfplot.datasets.load_example_data Source: https://surfplot.readthedocs.io/en/latest/api.html Loads example datasets that are useful for tutorials and demonstrations. ```APIDOC ## surfplot.datasets.load_example_data ### Description Load example datasets for tutorials. ### Function Signature `surfplot.datasets.load_example_data([...])` ``` -------------------------------- ### Install surfplot using pip Source: https://surfplot.readthedocs.io/en/latest/installation.html Use this command to install the surfplot library from the Python Package Index. ```bash pip install surfplot ``` -------------------------------- ### Load Example Statistical Data Source: https://surfplot.readthedocs.io/en/latest/auto_examples/plot_tutorial_01.html Loads example statistical data packaged with surfplot, which is pre-projected onto a fsLR surface. This data can then be added as a new layer. ```python from surfplot.datasets import load_example_data lh_data, rh_data = load_example_data() print(lh_data) ``` -------------------------------- ### load_example_data Source: https://surfplot.readthedocs.io/en/latest/generated/surfplot.datasets.load_example_data.html Loads example datasets for tutorials, specifically precomputed association maps for terms 'default mode' or 'frontoparietal' using Neurosynth. The maps are projected to fsLR space and their vertex arrays are saved. ```APIDOC ## surfplot.datasets.load_example_data ### Description Loads example datasets for tutorials. Precomputed association maps for terms ‘default mode’ or ‘frontoparietal’ using Neurosynth are downloaded, projected to fsLR space, and their vertex arrays are saved. ### Method Signature `load_example_data(_dataset ='default_mode'_, _join =False_)` ### Parameters #### Optional Parameters - **dataset** (str) - Neurosynth association map. Defaults to 'default_mode'. Accepts 'default_mode' or 'frontoparietal'. - **join** (bool) - Return data as a single concatenated array. Defaults to False, which returns left and right hemisphere arrays, respectively. ### Returns - **numpy.ndarray** - Vertex array(s) ``` -------------------------------- ### Fetch Surface Data Source: https://surfplot.readthedocs.io/en/latest/auto_examples/plot_tutorial_03.html Fetches FSLR surfaces and loads example data. This is a prerequisite for plotting. ```python from neuromaps.datasets import fetch_fslr from surfplot.datasets import load_example_data surfaces = fetch_fslr() lh, rh = surfaces['inflated'] ``` -------------------------------- ### Load Example Data Source: https://surfplot.readthedocs.io/en/latest/_modules/surfplot/datasets.html Loads precomputed Neurosynth association maps for 'default mode' or 'frontoparietal' terms. Use this function to fetch data for tutorial examples. It returns left and right hemisphere arrays by default, or a single concatenated array if 'join' is set to True. ```python import surfplot # Load default mode data (left and right hemispheres) left_data, right_data = surfplot.datasets.load_example_data() # Load frontoparietal data and join hemispheres joined_data = surfplot.datasets.load_example_data(dataset='frontoparietal', join=True) ``` -------------------------------- ### Multiple Stat Maps on a Surface Source: https://surfplot.readthedocs.io/en/latest/auto_examples/examples/plot_example_01.html This snippet shows how to overlay multiple statistical maps onto brain surfaces. It requires loading surface data and example statistical maps, then adding each map as a layer with specified colormaps and color ranges. Custom colorbar settings are applied for a cleaner visualization. ```python # Code source: Dan Gale # License: BSD 3 clause from surfplot import Plot from surfplot.datasets import load_example_data from neuromaps.datasets import fetch_fslr surfaces = fetch_fslr() lh, rh = surfaces['inflated'] p = Plot(lh, rh) # shading lh_sulc, rh_sulc = surfaces['sulc'] p.add_layer({'left': lh_sulc, 'right': rh_sulc}, cmap='binary_r', cbar=False) color_range = (0, 12) # add default mode association stats default = load_example_data(join=True) p.add_layer(default, cmap='Blues_r', color_range=color_range, cbar_label='Default mode') # add frontoparietal assocation stats fronto = load_example_data('frontoparietal', join=True) p.add_layer(fronto, cmap='Greens_r', color_range=color_range, cbar_label='Frontoparietal') # create a clean looking set of colorbars. Only show labels for outer colorbar, # given that both colorbars have the same range. cbar_kws = dict(outer_labels_only=True, pad=.02, n_ticks=2, decimals=0) fig = p.build(cbar_kws=cbar_kws) # add units to colorbar fig.axes[1].set_xlabel('z', labelpad=-11, fontstyle='italic') fig.show() ``` -------------------------------- ### Initialize Plotting Layers Source: https://surfplot.readthedocs.io/en/latest/_modules/surfplot/plotting.html Initializes internal lists for layers, colormaps, color ranges, and colorbar visibility/labels. Sets up a default gray backdrop layer with specified brightness. ```python # these are updated with each overlay self.layers, self.cmaps, self.color_ranges = [], [], [] self._show_cbar, self.cbar_labels = [], [] # add gray surface default: backdrop = np.ones(sum([v.n_points for v in self.surfaces.values()])) brightness = 1e-6 if brightness == 0 else brightness backdrop *= brightness self.add_layer(backdrop, 'Greys_r', color_range=(0, 1), cbar=False) ``` -------------------------------- ### load_example_data Source: https://surfplot.readthedocs.io/en/latest/docs/source/surfplot.html Loads precomputed association maps for specified datasets (e.g., 'default_mode', 'frontoparietal') for use in tutorials. Data can be returned as separate left/right hemisphere arrays or a single concatenated array. ```APIDOC ## surfplot.datasets.load_example_data ### Description Load example datasets for tutorials. Precomputed association maps for terms ‘default mode’ or ‘frontoparietal’ using Neurosynth. ### 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) ``` -------------------------------- ### show Source: https://surfplot.readthedocs.io/en/latest/docs/source/surfplot.html Displays the Brainspace vtk surface rendering, with options for embedding in notebooks and interactivity. ```APIDOC ## show ### Description 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 ``` -------------------------------- ### Plotting with File Paths for GIFTI/CIFTI Images Source: https://surfplot.readthedocs.io/en/latest/auto_examples/plot_tutorial_03.html Plots surface data directly from GIFTI or CIFTI file paths. A dictionary is required to assign files to hemispheres when plotting both. ```python lh_sulc, rh_sulc = surfaces['sulc'] p = Plot(surf_lh=lh, surf_rh=rh) p.add_layer({'left': lh_sulc, 'right': rh_sulc}, cmap='binary_r', cbar=False) fig = p.build() fig.show() ``` -------------------------------- ### Check and Prepare Data Source: https://surfplot.readthedocs.io/en/latest/_modules/surfplot/plotting.html Ensures input data is a numpy array of floats. Loads data from GIFTI or CIFTI files if provided. Flattens and converts data to float type. ```python def _check_data(data): """Ensure that data is of appropriate type and return numpy array""" if isinstance(data, np.ndarray): return data.astype(float) elif isinstance(data, (str, pathlib.PosixPath)): data = nib.load(data) elif isinstance(data, (nib.Cifti2Image, nib.GiftiImage)): pass else: raise TypeError('data must be a file path to a valid GIFTI or CIFTI ' \ 'file, or an instance of numpy.ndarray, ' \ 'nibabel.Cifti2Image nibabel.GiftiImage') if isinstance(data, nib.Cifti2Image): return data.get_fdata().ravel().astype(float) else: return data.agg_data().ravel().astype(float) ``` -------------------------------- ### Add Layer with Binary Colormap (No Colorbar) Source: https://surfplot.readthedocs.io/en/latest/auto_examples/plot_tutorial_05.html Initializes a plot with surface shading and adds a layer using a binary colormap. The colorbar is explicitly turned off. ```python from neuromaps.datasets import fetch_fslr from surfplot import Plot surfaces = fetch_fslr() lh, rh = surfaces['inflated'] p = Plot(lh, rh) sulc_lh, sulc_rh = surfaces['sulc'] p.add_layer({'left': sulc_lh, 'right': sulc_rh}, cmap='binary_r', cbar=False) ``` -------------------------------- ### Check Surface Type and Load Source: https://surfplot.readthedocs.io/en/latest/_modules/surfplot/plotting.html Validates the input surface type. Loads the surface from a file path if provided. Accepts file paths, BSPolyData objects, or None. ```python def _check_surf(surf): """Validate surface type and load if a file name""" if isinstance(surf, (str, pathlib.Path)): return read_surface(str(surf)) elif isinstance(surf, BSPolyData) or (surf is None): return surf else: raise ValueError('Surface be a path-like string, an instance of ' \ 'BSPolyData, or None') ``` -------------------------------- ### surfplot.surf Function Implementation Source: https://surfplot.readthedocs.io/en/latest/_modules/surfplot/surf.html This snippet shows the core implementation of the surfplot.surf function. It handles conditional logic for screenshots and notebook embedding, builds the plotter, and then either returns the plotter, saves a screenshot, or displays the plot. ```python if screenshot and filename is None: raise ValueError('Filename is required.') if screenshot or embed_nb: kwargs.update({'offscreen': True}) p = build_plotter(surfs, layout, array_name=array_name, view=view, color_bar=color_bar, color_range=color_range, share=share, label_text=label_text, cmap=cmap, nan_color=nan_color, zoom=zoom, background=background, size=size, **kwargs) if return_plotter: return p if screenshot: return p.screenshot(filename, transparent_bg=transparent_bg, scale=scale) return p.show(embed_nb=embed_nb, interactive=interactive, scale=scale, transparent_bg=transparent_bg) ``` -------------------------------- ### Build Plot with Customized Colorbar Keywords Source: https://surfplot.readthedocs.io/en/latest/auto_examples/plot_tutorial_05.html Builds the plot with custom keyword arguments for colorbar styling, including location, label direction, tick formatting, and size adjustments. ```python kws = {'location': 'right', 'label_direction': 45, 'decimals': 1, 'fontsize': 8, 'n_ticks': 2, 'shrink': .15, 'aspect': 8, 'draw_border': False} fig = p.build(cbar_kws=kws) fig.show() # sphinx_gallery_thumbnail_number = 3 ``` -------------------------------- ### Adjusting Surface Brightness Source: https://surfplot.readthedocs.io/en/latest/auto_examples/plot_tutorial_02.html Demonstrates how to adjust the brightness of the blank surface when plotting. The brightness parameter ranges from 0 (black) to 1 (white). ```python p = Plot(lh, rh, brightness=.8) fig = p.build() fig.show() ``` -------------------------------- ### show Source: https://surfplot.readthedocs.io/en/latest/generated/surfplot.plotting.Plot.html Displays a Brainspace vtk surface rendering. This method is intended to show surface plots generated by `brainspace.plotting.surface_plotting.plot_surf` and does not incorporate colorbars or other matplotlib elements. ```APIDOC ## show ### Description View Brainspace vtk surface rendering. This method 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. ### Method This is a method call within the `surfplot.plotting.Plot` class. ### Parameters #### Optional 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 - **transparent_bg** (_bool_) - Optional - Whether the background should be transparent. Default: True - **scale** (_tuple_) - Optional - Amount to scale the surface plot. Default: (1, 1) ### Returns - _Ipython Image or vtk panel_ – Brainspace surface plot rendering ``` -------------------------------- ### Helper Function: Set Colorbar Labels Source: https://surfplot.readthedocs.io/en/latest/_modules/surfplot/plotting.html Adds labels to a colorbar, adjusting position and orientation based on the specified location. Requires a valid location string. ```python def _set_colorbar_labels(cbar, label, location, fontsize=10, rotation=None): """Add colorbar labels to drawn colorbar""" valid_locations = ['top', 'bottom', 'left', 'right'] if location not in valid_locations: raise ValueError(f"`location` must be one of {valid_locations}") rotation, ha, va = _set_label_positions(location, rotation) label_args = dict(rotation=rotation, ha=ha, va=va, fontsize=fontsize) if location in ['top', 'bottom']: cbar.ax.set_ylabel(label, **label_args) else: cbar.ax.set_title(label, pad=10, **label_args) return cbar ``` -------------------------------- ### build Source: https://surfplot.readthedocs.io/en/latest/_modules/surfplot/plotting.html Builds a matplotlib figure of the surface plot with optional colorbars. ```APIDOC ## build ### Description Constructs and returns a matplotlib figure object representing the surface plot. It renders the plot, converts it to a NumPy array, and then displays it using matplotlib. Colorbars can be optionally added. ### Parameters - **figsize** (tuple, optional): The overall figure size (width, height). If None, it's determined by the `size` parameter. Defaults to None. - **colorbar** (bool, optional): Whether to draw colorbars for applicable layers. Defaults to True. - **cbar_kws** (dict, optional): Keyword arguments to pass to the `_add_colorbar` function for customizing colorbars. Defaults to None. - **scale** (tuple, optional): Scaling factor for the surface plot rendering. Defaults to (2, 2). ### Returns - matplotlib.pyplot.figure: The generated matplotlib figure object containing the surface plot. ``` -------------------------------- ### Create a Basic Brain Plot Source: https://surfplot.readthedocs.io/en/latest/auto_examples/plot_tutorial_01.html Initializes the Plot class with left and right hemisphere surfaces and builds the initial figure. This sets up the canvas for adding data layers. ```python from surfplot import Plot p = Plot(surf_lh=lh, surf_rh=rh) fig = p.build() # show figure, as you typically would with matplotlib fig.show() ``` -------------------------------- ### build Source: https://surfplot.readthedocs.io/en/latest/generated/surfplot.plotting.Plot.html Builds a matplotlib figure of the surface plot with optional colorbars and scaling. ```APIDOC ## build ### Description Build matplotlib figure of surface plot ### Parameters #### Figure Size - **figsize** (tuple, optional) - Overall figure size, specified by (width, height). Default: None, which will determine the figure size based on the size parameter. #### Colorbar Display - **colorbar** (bool, optional) - Draw colorbars for each applicable layer, default: True #### Colorbar Keyword Arguments - **cbar_kws** (dict, optional) - Keyword arguments for `_add_colorbar()`. Default: None, which will plot the default colorbar parameters. #### Scaling - **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 ``` -------------------------------- ### surfplot.surf.build_plotter Source: https://surfplot.readthedocs.io/en/latest/docs/source/surfplot.html Builds a plotter arranged according to a specified layout, allowing for customization of views, color bars, color ranges, and more. ```APIDOC ## surfplot.surf.build_plotter ### Description 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. If `share == 'col'`, the same but for columns. If `share == 'both'`, all data shares same range. If True, similar to `share == '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. ``` -------------------------------- ### Fetch Brain Surfaces Source: https://surfplot.readthedocs.io/en/latest/auto_examples/plot_tutorial_01.html Imports the necessary function to fetch brain surface data. This is the first step to preparing data for plotting. ```python from neuromaps.datasets import fetch_fslr surfaces = fetch_fslr() lh, rh = surfaces['inflated'] ``` -------------------------------- ### Default Plot Layout and View Source: https://surfplot.readthedocs.io/en/latest/auto_examples/plot_tutorial_04.html Creates a default 2x2 grid layout with lateral and medial views for both hemispheres, identical to Connectome Workbench's default. ```python from brainspace.datasets import load_conte69 from surfplot import Plot lh, rh = load_conte69() p = Plot(lh, rh) fig = p.build() fig.show() ``` -------------------------------- ### Build Plotter with Layout Source: https://surfplot.readthedocs.io/en/latest/_modules/surfplot/surf.html Builds a plotter object arranged according to a specified layout. It accepts various arguments to customize the plot, including surfaces, view, color bar, color range, labels, colormap, background, and size. ```python def 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): """Build plotter arranged according to the `layout`. ``` -------------------------------- ### Plot Class Initialization Source: https://surfplot.readthedocs.io/en/latest/_modules/surfplot/plotting.html Initializes the Plot class for visualizing brain surfaces. Accepts surface data for left and right hemispheres, layout options, views, and visual parameters. Raises ValueError if no surfaces are provided. ```python class Plot(object): """Plot brain surfaces with data layers Parameters ---------- surf_lh, surf_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 :func:`brainspace.mesh.mesh_io.read_surface`. At least one hemisphere must be provided. Default: None layout : {'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 """ def __init__(self, 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=.5): hemi_inputs = zip(['left', 'right'], [surf_lh, surf_rh]) self.surfaces = {k: _check_surf(v) for k, v in hemi_inputs if v is not None} if len(self.surfaces) == 0: raise ValueError('No surfaces are provided') if views == None: views = ['lateral', 'medial'] self.plot_layout = _set_layout(surf_lh, surf_rh, layout, views, mirror_views) self.flip = flip # plot_surf args self.size = size self.zoom = zoom self.background = background self.label_text = label_text ``` -------------------------------- ### Add Layer with Colormap and Colorbar Label Source: https://surfplot.readthedocs.io/en/latest/auto_examples/plot_tutorial_05.html Adds a plotting layer with a specified colormap and a descriptive label for its colorbar. The plot is then built and displayed. ```python from surfplot.datasets import load_example_data # default mode network associations default = load_example_data(join=True) p.add_layer(default, cmap='GnBu_r', cbar_label='Default mode') fig = p.build() fig.show() ``` -------------------------------- ### surfplot.surf Function Definition Source: https://surfplot.readthedocs.io/en/latest/_modules/surfplot/surf.html This snippet shows the function signature and docstring for surfplot.surf. It details the parameters for controlling surface visualization, data plotting, and output options. ```python def 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=None, background=(1, 1, 1), size=(400, 400), interactive=True, embed_nb=False, screenshot=False, filename=None, transparent_bg=False, scale=None, return_plotter=False, **kwargs): """ Plot surfaces. 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. If ``share == 'col'``, the same but for columns. If ``share == 'both'``, all data shares same range. If True, similar to ``share == '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 -------- :func:`build_plotter` :func:`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 Function Parameters Source: https://surfplot.readthedocs.io/en/latest/_modules/surfplot/surf.html This section outlines the parameters for the surfplot.surf function, including surface data, layout specifications, array names for plotting, view options, color bar placement, color range settings, data sharing options, label text customization, colormaps, NaN color handling, zoom levels, background color, window size, and additional keyword arguments for renderers, actors, mappers, and plotters. ```python def surf(surfs: dict[str, BSPolyData], layout: array-like, array_name: array-like = None, view: array-like = None, color_bar: {'left', 'right', 'top', 'bottom'} | None = None, color_range: {'sym'} | tuple | sequence = None, share: {'row', 'col', 'both'} | bool = False, label_text: dict[str, array-like] = None, cmap: str | sequence[str] = 'viridis', nan_color: tuple = (0, 0, 0, 1), zoom: float | sequence[float] = None, background: tuple = (1, 1, 1), size: tuple = (400, 400), **kwargs): """ 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. If ``share == 'col'``, the same but for columns. If ``share == 'both'``, all data shares same range. If True, similar to ``share == '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 -------- :func:`plot_surf` :func:`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`. """ # Layout for k in np.unique(layout): if k not in surfs and k is not None: raise ValueError("Key '%s' is not in 'surfs'" % k) # Share if share is True: share = 'b' elif share is None or share is False: share = None elif share in {'row', 'r', 'col', 'c', 'both', 'b'}: share = share[0] else: raise ValueError("Unknown share=%s" % share) # Color bar if color_bar is True: color_bar = 'right' elif color_bar is None or color_bar is False: color_bar = None elif color_bar not in {'left', 'right', 'top', 'bottom'}: raise ValueError("Unknown color_bar=%s" % color_bar) if share == 'c' and color_bar in {'left', 'right'}: raise ValueError("Incompatible color_bar=%s and " "share=%s" % (color_bar, share)) if share == 'r' and color_bar in {'top', 'bottom'}: raise ValueError("Incompatible color_bar=%s and " "share=%s" % (color_bar, share)) layout = np.atleast_2d(layout) nrow, ncol = shape = layout.shape view = _broadcast(view, 'view', shape) zoom = _broadcast(zoom, 'zoom', shape) array_name = _expand_arg(array_name, 'array_name', shape) cmap = _expand_arg(cmap, 'cmap', shape, ref=array_name) color_range = _expand_arg(color_range, 'cbar_range', shape, ref=array_name) ren_kwds = _grep_args('renderer', kwargs, shape=shape) actor_kwds = _grep_args('actor', kwargs, shape=shape, ref=array_name) mapper_kwds = _grep_args('mapper', kwargs, shape=shape, ref=array_name) cb_kwds = _grep_args('cb', kwargs) text_kwds = _grep_args('text', kwargs) # lut_kwds = _grep_args('lut', kwargs) ``` -------------------------------- ### Plotting Freesurfer fsaverage Surfaces Source: https://surfplot.readthedocs.io/en/latest/auto_examples/plot_tutorial_02.html Fetches fsaverage surfaces using neuromaps and plots them using surfplot. Ensure you have the correct surface for your data and double-check vertex counts. ```python from neuromaps.datasets import fetch_fsaverage from surfplot import Plot surfaces = fetch_fsaverage(density='164k') lh, rh = surfaces['inflated'] # make figure p = Plot(lh, rh) fig = p.build() fig.show() ``` -------------------------------- ### Set Colormap Lookup Table Source: https://surfplot.readthedocs.io/en/latest/_modules/surfplot/surf.html Generates a NumPy array representing a colormap's lookup table based on a given colormap name and number of values. The output is an array of uint8 values scaled from 0 to 255. ```python def _set_table(cm, lut): cm = plt.get_cmap(cm) nvals = lut['numberOfTableValues'] table = cm(np.linspace(0, 1, nvals)) * 255 return table.astype(np.uint8) ``` -------------------------------- ### render Source: https://surfplot.readthedocs.io/en/latest/generated/surfplot.plotting.Plot.html Generates the surface plot with all added layers, with an option for offscreen rendering. ```APIDOC ## render ### Description Generate surface plot with all provided layers ### Parameters #### Offscreen Rendering - **offscreen** (bool, optional) - Render offscreen. Default: True ### Returns - **brainspace.plotting.base.Plotter** - Surface plot ``` -------------------------------- ### Plotting with Loaded Nibabel Image Objects Source: https://surfplot.readthedocs.io/en/latest/auto_examples/plot_tutorial_03.html Plots surface data from a nibabel image object that has already been loaded. This is useful when you have pre-loaded image data. ```python img = nib.load(lh_sulc) p = Plot(surf_lh=lh, zoom=1.2, size=(400, 200)) p.add_layer(img, cmap='binary_r', cbar=False) fig = p.build() fig.show() ``` -------------------------------- ### Rendering Surface Plot Source: https://surfplot.readthedocs.io/en/latest/_modules/surfplot/plotting.html Generates a surface plot with all provided layers. Supports offscreen rendering and flexible layout configurations. Returns a Plotter object. ```python view_layout, hemi_layout = self.plot_layout dimensions = np.array(view_layout).shape if self.flip and len(self.surfaces) == 2: view_layout, hemi_layout = _flip_hemispheres(view_layout, hemi_layout) # create plot tuples layers = PTuple(*self.layers) cmaps = PTuple(*self.cmaps) crange = PTuple(*self.color_ranges) if all(i != 1 for i in dimensions) and (len(dimensions) == 2): # grid layout names = [[layers] * dimensions[1]] * dimensions[0] cmap = [cmaps] * dimensions[1] color_range = [crange] * dimensions[1] else: # column or row layout names = [layers] cmap = [cmaps] color_range = [crange] return plot_surf(surfs=self.surfaces, layout=hemi_layout, array_name=names, cmap=cmap, color_bar=False, color_range=color_range, view=view_layout, background=self.background, zoom=self.zoom, nan_color=(0, 0, 0, 0), share=False, label_text=self.label_text, size=self.size, return_plotter=True, offscreen=offscreen) ``` -------------------------------- ### Plotting Surfaces with Surfplot Source: https://surfplot.readthedocs.io/en/latest/_modules/surfplot/surf.html This function is used to plot surfaces arranged according to a specified layout. It supports various customization options for color bars, labels, views, and output formats. ```python def 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): """Plot surfaces arranged according to the `layout`. ``` -------------------------------- ### Add Second Layer with Different Colormap and Label Source: https://surfplot.readthedocs.io/en/latest/auto_examples/plot_tutorial_05.html Adds another plotting layer with a distinct colormap and colorbar label to demonstrate multi-layer colorbar functionality. The plot is rebuilt and shown. ```python fronto = load_example_data('frontoparietal', join=True) p.add_layer(fronto, cmap='YlOrBr_r', cbar_label='Frontoparietal') fig = p.build() fig.show() ``` -------------------------------- ### Adding Surface Layers and Colormaps Source: https://surfplot.readthedocs.io/en/latest/_modules/surfplot/plotting.html Appends surface data with specified colormaps and color ranges. Handles transparency and outlines. Used internally for managing plot layers. ```python for k, v in self.surfaces.items(): if k in vertices.keys(): if as_outline: x = get_labeling_border( v, np.nan_to_num(vertices[k]) ).astype(float) else: x = vertices[k] if zero_transparent: x[x == 0] = np.nan v.append_array(x, name=name, at='p') else: # blank layer for unspecified hemisphere x = np.zeros(v.n_points) x[x == 0] = np.nan v.append_array(x, name=name, at='p') if alpha < 1: if isinstance(cmap, str): cmap = plt.get_cmap(cmap) cmapV = cmap(np.arange(cmap.N)) cmapV[:, -1] = alpha cmap = mpl.colors.ListedColormap(cmapV) self.layers.append(name) self.cmaps.append(cmap) if color_range is None: self.color_ranges.append(_find_color_range(vertices)) else: self.color_ranges.append(color_range) self._show_cbar.append(cbar) self.cbar_labels.append(cbar_label) ``` -------------------------------- ### Plotting Volumetric Data on Surfaces Source: https://surfplot.readthedocs.io/en/latest/auto_examples/examples/plot_example_02.html This snippet shows the complete process of fetching, projecting, thresholding, and plotting volumetric neuroimaging data onto brain surfaces. It requires nilearn, neuromaps, and surfplot libraries. ```python # Code source: Dan Gale # License: BSD 3 clause from nilearn.datasets import fetch_neurovault_ids from nilearn.plotting.cm import _cmap_d as nilearn_cmaps from neuromaps.transforms import mni152_to_fslr from neuromaps.datasets import fetch_fslr from surfplot import Plot from surfplot.utils import threshold data = fetch_neurovault_ids(image_ids=[47307], verbose=0) img = data['images'][0] # project from MNI to fslr; GIFTI surfaces are returned gii_lh, gii_rh = mni152_to_fslr(img) # threshold after projection to avoid interpolation artefacts data_lh = threshold(gii_lh.agg_data(), 3) data_rh = threshold(gii_rh.agg_data(), 3) # get surfaces + sulc maps surfaces = fetch_fslr() lh, rh = surfaces['inflated'] sulc_lh, sulc_rh = surfaces['sulc'] p = Plot(lh, rh) p.add_layer({'left': sulc_lh, 'right': sulc_rh}, cmap='binary_r', cbar=False) # cold_hot is a common diverging colormap for neuroimaging cmap = nilearn_cmaps['cold_hot'] p.add_layer({'left': data_lh, 'right': data_rh}, cmap=cmap, color_range=(-11, 11)) # make a nice vertical colorbar on the right side of the figure kws = dict(location='right', draw_border=False, aspect=10, shrink=.2, decimals=0, pad=0) fig = p.build(cbar_kws=kws) fig.axes[0].set_title('MSC05 Left > Right Hand', pad=-3) fig.show() ```