Skip to content

plotting API

yabplot.plotting.plot_cortical(data=None, atlas=None, custom_atlas_path=None, ax=None, cbar_kwargs=None, views=None, layout=None, bmesh='midthickness', figsize=None, cmap='coolwarm', vminmax=[None, None], nan_color=(1.0, 1.0, 1.0), style='default', zoom=1.2, proc_vertices='sharp', display_type='matplotlib', export_path=None, contours=False)

Visualize data on the cortical surface using a specified atlas.

This function maps scalar values to cortical regions (parcellations) on a standard surface mesh (Conte69). It supports both pre-existing atlases and custom local atlases.

Parameters:

Name Type Description Default
data (dict, list, ndarray)

Data to map onto the cortex. If dict: Keys must match region names in the atlas (see yabplot.get_atlas_regions). If array/list: Must match the exact length and order of the atlas regions. If None: The atlas is plotted with categorical colors (one color per region).

None
atlas str

Name of the standard atlas to use (e.g., 'schaefer_100', see 'yabplot.get_available_resources' for more). Defaults to 'aparc' if neither atlas nor custom_atlas_path is provided.

None
custom_atlas_path str

Path to a local directory containing custom atlas files. The directory must contain a CSV mapping regions to vertices and a LUT text file. If provided, atlas is ignored.

None
views list of str

Views to display. Can be a list of presets ('left_lateral', 'right_medial', etc.) or a dictionary of camera configurations. Defaults to all views.

None
layout tuple(rows, cols)

Grid layout for subplots. If None, automatically calculated based on the number of views.

None
bmesh str

Name of the background context brain mesh (e.g., 'midthickness', 'white', 'swm', etc). Default is 'midthickness'.

'midthickness'
figsize tuple(width, height)

Window size in inches. If None, automatically calculated based on the number of views and layout.

None
cmap str or Colormap

Colormap for continuous data. Ignored if data is None. Default is 'RdYlBu_r'.

'coolwarm'
vminmax list[min, max]

Manual lower and upper bounds for the colormap. If [None, None], bounds are inferred from the data range.

[None, None]
nan_color tuple or str

Color for regions with missing (NaN) data or the medial wall. Default is white.

(1.0, 1.0, 1.0)
style str

Lighting preset ('default', 'matte', 'glossy', 'sculpted', 'flat').

'default'
zoom float

Camera zoom level. >1.0 zooms in, <1.0 zooms out. Default is 1.2.

1.2
proc_vertices str or None

Whether to process the vertices edges according to geometry of bmesh. Set to None to not perform. 'blur': Applies simple blurring between different color vertices. 'sharp': Applies sharpening of the resolution of different color vertices (default).

'sharp'
display_type (matplotlib, interactive, pyvista, object)

'matplotlib': returns a matplotlib figure and axis (default). 'interactive': opens an interactive trame viewer in the browser. 'pyvista': returns a static jupyter widget (legacy behavior). 'object': returns the raw pyvista plotter object.

'matplotlib'
export_path str

If provided, saves the final figure to this path (e.g., 'figure.png').

None
contours bool, dict, list, str, or numpy.ndarray

Draw boundary lines between atlas regions. Default False. Four forms:

  • True: all regions, default style (black, 1 mm wide, opaque).
  • style dict (values are primitives): all regions, custom style. Keys: color, line_width (width in mm on the surface, default 1.0), opacity, include_nan. include_nan=False suppresses borders between two NaN regions while keeping outlines around regions that have data. Default True.
  • list of region name strings (or a single name) or bool ndarray (one value per region, in the same order as array data): those regions only, default style.
  • region dict (values are dicts): only the listed regions, each style dict merged with the global defaults. Same keys as style dict.
False

Returns:

Type Description
Axes or Plotter or DisplayObject

returns based on display_type: - 'matplotlib': returns a matplotlib axes object. - 'interactive': returns a trame browser viewer. - 'pyvista': returns a static jupyter widget. - 'object': returns the raw pyvista plotter.

Source code in yabplot/plotting.py
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
def plot_cortical(data=None, atlas=None, custom_atlas_path=None, ax=None, cbar_kwargs=None, views=None, layout=None,
                  bmesh='midthickness', figsize=None, cmap='coolwarm', vminmax=[None, None],
                  nan_color=(1.0, 1.0, 1.0), style='default', zoom=1.2, proc_vertices='sharp',
                  display_type='matplotlib', export_path=None, contours=False):
    """
    Visualize data on the cortical surface using a specified atlas.

    This function maps scalar values to cortical regions (parcellations) on a standard
    surface mesh (Conte69). It supports both pre-existing atlases and custom local atlases.

    Parameters
    ----------
    data : dict, list, numpy.ndarray, optional
        Data to map onto the cortex.
        If dict: Keys must match region names in the atlas (see `yabplot.get_atlas_regions`).
        If array/list: Must match the exact length and order of the atlas regions.
        If None: The atlas is plotted with categorical colors (one color per region).
    atlas : str, optional
        Name of the standard atlas to use (e.g., 'schaefer_100',
        see 'yabplot.get_available_resources' for more).
        Defaults to 'aparc' if neither atlas nor custom_atlas_path is provided.
    custom_atlas_path : str, optional
        Path to a local directory containing custom atlas files. The directory must
        contain a CSV mapping regions to vertices and a LUT text file. If provided, `atlas` is ignored.
    views : list of str, optional
        Views to display. Can be a list of presets ('left_lateral', 'right_medial', etc.)
        or a dictionary of camera configurations. Defaults to all views.
    layout : tuple (rows, cols), optional
        Grid layout for subplots. If None, automatically calculated based on the number of views.
    bmesh : str
        Name of the background context brain mesh (e.g., 'midthickness', 'white', 'swm', etc).
        Default is 'midthickness'.
    figsize : tuple (width, height), optional
        Window size in inches. If None, automatically calculated based on the number of views and layout.
    cmap : str or matplotlib.colors.Colormap, optional
        Colormap for continuous data. Ignored if `data` is None. Default is 'RdYlBu_r'.
    vminmax : list [min, max], optional
        Manual lower and upper bounds for the colormap. If [None, None],
        bounds are inferred from the data range.
    nan_color : tuple or str, optional
        Color for regions with missing (NaN) data or the medial wall. Default is white.
    style : str, optional
        Lighting preset ('default', 'matte', 'glossy', 'sculpted', 'flat').
    zoom : float, optional
        Camera zoom level. >1.0 zooms in, <1.0 zooms out. Default is 1.2.
    proc_vertices : str or None, optional
        Whether to process the vertices edges according to geometry of bmesh.
        Set to None to not perform.
        'blur': Applies simple blurring between different color vertices.
        'sharp': Applies sharpening of the resolution of different color vertices (default).
    display_type : {'matplotlib', 'interactive', 'pyvista', 'object'}, optional
        'matplotlib': returns a matplotlib figure and axis (default).
        'interactive': opens an interactive trame viewer in the browser.
        'pyvista': returns a static jupyter widget (legacy behavior).
        'object': returns the raw pyvista plotter object.
    export_path : str, optional
        If provided, saves the final figure to this path (e.g., 'figure.png').
    contours : bool, dict, list, str, or numpy.ndarray, optional
        Draw boundary lines between atlas regions. Default ``False``. Four forms:

        - ``True``: all regions, default style (black, 1 mm wide, opaque).
        - **style dict** (values are primitives): all regions, custom style.
          Keys: ``color``, ``line_width`` (width in mm on the surface, default ``1.0``),
          ``opacity``, ``include_nan``.
          ``include_nan=False`` suppresses borders between two NaN regions while
          keeping outlines around regions that have data. Default ``True``.
        - **list** of region name strings (or a single name) or **bool ndarray**
          (one value per region, in the same order as array ``data``):
          those regions only, default style.
        - **region dict** (values are dicts): only the listed regions, each
          style dict merged with the global defaults. Same keys as style dict.

    Returns
    -------
    matplotlib.axes.Axes or pyvista.Plotter or IPython.display.DisplayObject
        returns based on display_type:
        - 'matplotlib': returns a matplotlib axes object.
        - 'interactive': returns a trame browser viewer.
        - 'pyvista': returns a static jupyter widget.
        - 'object': returns the raw pyvista plotter.
    """

    # atlas and categorical check
    if atlas is None and custom_atlas_path is None:
        atlas = 'aparc'
    is_cat = (data is None)

    # load brain mesh
    b_lh_path, b_rh_path = get_surface_paths(bmesh, 'bmesh')
    lh_v, lh_f = load_gii(b_lh_path)
    rh_v, rh_f = load_gii(b_rh_path)

    # resolve atlas
    atlas_dir = _resolve_resource_path(atlas, 'cortical', custom_path=custom_atlas_path)
    check_name = None if custom_atlas_path else atlas
    csv_path, lut_path = _find_cortical_files(atlas_dir, strict_name=check_name)

    # load mapping data
    tar_labels = np.loadtxt(csv_path, dtype=int)
    lut_ids, lut_colors, lut_names, max_id = parse_lut(lut_path)

    # map data
    all_vals = map_values_to_surface(data, tar_labels, lut_ids, lut_names)
    lh_vals_raw = all_vals[:len(lh_v)]
    rh_vals_raw = all_vals[len(lh_v):]

    # compute region boundary contours
    contour_layers = None
    if contours is not False and contours is not None:
        n_lh = len(lh_v)
        contour_layers = _build_contour_layers(
            contours, lh_v, lh_f, rh_v, rh_f,
            tar_labels, lh_vals_raw, rh_vals_raw,
            lut_ids, lut_names, n_lh
        )

    # render
    return _render_cortical_views(
        lh_v, lh_f, lh_vals_raw, rh_v, rh_f, rh_vals_raw, is_cat, ax, cbar_kwargs,
        views, layout, figsize, cmap, vminmax, nan_color, style,
        zoom, proc_vertices, display_type, export_path, lut_colors, max_id,
        contour_layers
    )

yabplot.plotting.plot_subcortical(data=None, atlas=None, custom_atlas_path=None, ax=None, cbar_kwargs=None, views=None, layout=None, figsize=None, cmap=None, vminmax=[None, None], nan_color='#cccccc', nan_alpha=1.0, style='default', bmesh='midthickness', bmesh_alpha=0.15, bmesh_color='lightgray', zoom=1.2, display_type='matplotlib', export_path=None, custom_atlas_proc=dict(smooth_i=15, smooth_f=0.6), atlas_color_seed=42, plot_regions_separately=False, shared_hemisphere_colors=False)

Visualize data on the subcortical structures using a specified atlas.

Renders volumetric structures as 3D meshes. Supports pre-existing atlases and on-the-fly conversion of GIfTI surfaces to smooth meshes for custom atlases.

Parameters:

Name Type Description Default
data (dict, list, ndarray, Series, DataFrame)

Scalar values for each subcortical region. If dict/pd.Series/pd.DataFrame: Values according to region names. If array/list: Must strictly match the sorted order of regions in the atlas.

None
atlas str

Name of the standard atlas to use (e.g., 'musus_100', see 'yabplot.get_available_resources' for more). Defaults to 'aseg' if neither atlas nor custom_atlas_path is provided.

None
custom_atlas_path str

Path to a local directory containing .vtk or .gii mesh files for each region.

None
views list of str

Views to display. Can be a list of presets ('left_lateral', 'right_medial', etc.) or a dictionary of camera configurations. Defaults to all views.

None
layout tuple(rows, cols)

Grid layout for subplots. If None, automatically calculated based on the number of views.

None
figsize tuple(width, height)

Window size in inches. If None, automatically calculated based on the number of views and layout.

None
cmap str or Colormap

Colormap for continuous data. Defaults to 'coolwarm' when data is given. If data is None (atlas mode), cmap is unused by default and regions get randomly-seeded distinct colors; pass a colormap (name or object) to instead sample region colors from that colormap's gradient.

None
vminmax list[min, max]

Manual lower and upper bounds for the colormap. If [None, None], bounds are inferred from the data range.

[None, None]
nan_color str or tuple

Color for regions with no data (NaN). Default is light grey '#cccccc'.

'#cccccc'
nan_alpha float

Opacity (0.0 to 1.0) for regions with no data. Set to 0.0 to hide them.

1.0
style str

Lighting preset ('default', 'matte', 'glossy', 'sculpted', 'flat').

'default'
bmesh PolyData or dict

Configure background context brain mesh. Accepts a string (e.g., 'midthickness', 'white', 'swm', etc), single PolyData (used for both hemispheres) or a dict with 'L'/'R' keys. Default is 'midthickness'.

'midthickness'
bmesh_alpha float

Opacity of the context brain mesh. Default is 0.15.

0.15
bmesh_color str

Color of the context brain mesh.

'lightgray'
zoom float

Camera zoom level. >1.0 zooms in, <1.0 zooms out. Default is 1.2.

1.2
display_type (matplotlib, interactive, pyvista, object)

'matplotlib': returns a matplotlib figure and axis (default). 'interactive': opens an interactive trame viewer in the browser. 'pyvista': returns a static jupyter widget (legacy behavior). 'object': returns the raw pyvista plotter object.

'matplotlib'
export_path str

If provided, saves the final figure to this path (e.g., 'figure.png'). With plot_regions_separately, it is instead the directory that the per-region PNGs are saved to.

None
custom_atlas_proc dict

Parameters for processing custom GIfTI files. Keys: 'smooth_i' (iterations) and 'smooth_f' (relaxation factor). Default is {'smooth_i': 15, 'smooth_f': 0.6}.

dict(smooth_i=15, smooth_f=0.6)
atlas_color_seed int

Seed controlling the categorical color arrangement in atlas (no-data) mode. With the default palette it seeds the distinct-color generator; with a colormap it seeds a shuffle so gradient-adjacent regions get contrasting colors. Change it to get a different, reproducible arrangement. Ignored when data is given. Default is 42.

42
plot_regions_separately bool

If True, renders each region + view combination on its own instead of a single combined figure. If export_path is set, it is always treated as a directory (created if missing): one transparent-background PNG per region + view is saved there (named {region}_{view_face}.png, useful for SVG tracing pipelines) and None is returned. view_face is the view name without left_/right_; midline regions keep the full view name. Otherwise one matplotlib figure per region + view is opened and the axes are returned as a list. All renders share the same camera framing, so regions keep their relative position and size, and the same size: figsize if given, else 3.5 x 3 inches. ax, layout, display_type and cbar_kwargs are not used in this mode and no colorbar is drawn. Default is False.

False
shared_hemisphere_colors bool

If True, bilateral region pairs (e.g. putamen_l / putamen_r) are drawn in the same color, so each structure reads as one color across both hemispheres. Pairs are matched by name after removing one hemisphere tag (case-insensitive): a _l/_r or -lh/-rh suffix, or a l-/r-, l_/r_, left_/right_ or left-/right- prefix. Regions named in any other way keep their own color. Only applies in atlas (no-data) mode; ignored when data is given. If False (default), every region is assigned its own independent color.

False

Returns:

Type Description
Axes or Plotter or DisplayObject

returns based on display_type: - 'matplotlib': returns a matplotlib axes object. - 'interactive': returns a trame browser viewer. - 'pyvista': returns a static jupyter widget. - 'object': returns the raw pyvista plotter. with plot_regions_separately, returns None if export_path is set, otherwise a list of matplotlib axes (one per region + view).

Source code in yabplot/plotting.py
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
def plot_subcortical(data=None, atlas=None, custom_atlas_path=None, ax=None, cbar_kwargs=None, views=None, layout=None,
                     figsize=None, cmap=None, vminmax=[None, None], nan_color='#cccccc',
                     nan_alpha=1.0, style='default', bmesh='midthickness',
                     bmesh_alpha=0.15, bmesh_color='lightgray', zoom=1.2, display_type='matplotlib',
                     export_path=None, custom_atlas_proc=dict(smooth_i=15, smooth_f=0.6),
                     atlas_color_seed=42, plot_regions_separately=False,
                     shared_hemisphere_colors=False):
    """
    Visualize data on the subcortical structures using a specified atlas.

    Renders volumetric structures as 3D meshes. Supports pre-existing atlases and
    on-the-fly conversion of GIfTI surfaces to smooth meshes for custom atlases.

    Parameters
    ----------
    data : dict, list, numpy.ndarray, pandas.Series, pandas.DataFrame, optional
        Scalar values for each subcortical region.
        If dict/pd.Series/pd.DataFrame: Values according to region names.
        If array/list: Must strictly match the sorted order of regions in the atlas.
    atlas : str, optional
        Name of the standard atlas to use (e.g., 'musus_100',
        see 'yabplot.get_available_resources' for more).
        Defaults to 'aseg' if neither atlas nor custom_atlas_path is provided.
    custom_atlas_path : str, optional
        Path to a local directory containing .vtk or .gii mesh files for each region.
    views : list of str, optional
        Views to display. Can be a list of presets ('left_lateral', 'right_medial', etc.)
        or a dictionary of camera configurations. Defaults to all views.
    layout : tuple (rows, cols), optional
        Grid layout for subplots. If None, automatically calculated based on the number of views.
    figsize : tuple (width, height), optional
        Window size in inches. If None, automatically calculated based on the number of views and layout.
    cmap : str or matplotlib.colors.Colormap, optional
        Colormap for continuous data. Defaults to 'coolwarm' when `data` is given.
        If `data` is None (atlas mode), `cmap` is unused by default and regions get
        randomly-seeded distinct colors; pass a colormap (name or object) to instead
        sample region colors from that colormap's gradient.
    vminmax : list [min, max], optional
        Manual lower and upper bounds for the colormap. If [None, None],
        bounds are inferred from the data range.
    nan_color : str or tuple, optional
        Color for regions with no data (NaN). Default is light grey '#cccccc'.
    nan_alpha : float, optional
        Opacity (0.0 to 1.0) for regions with no data. Set to 0.0 to hide them.
    style : str, optional
        Lighting preset ('default', 'matte', 'glossy', 'sculpted', 'flat').
    bmesh : pyvista.PolyData or dict, optional
        Configure background context brain mesh. Accepts a string
        (e.g., 'midthickness', 'white', 'swm', etc), single PolyData (used for both hemispheres)
        or a dict with 'L'/'R' keys. Default is 'midthickness'.
    bmesh_alpha : float, optional
        Opacity of the context brain mesh. Default is 0.15.
    bmesh_color : str, optional
        Color of the context brain mesh.
    zoom : float, optional
        Camera zoom level. >1.0 zooms in, <1.0 zooms out. Default is 1.2.
    display_type : {'matplotlib', 'interactive', 'pyvista', 'object'}, optional
        'matplotlib': returns a matplotlib figure and axis (default).
        'interactive': opens an interactive trame viewer in the browser.
        'pyvista': returns a static jupyter widget (legacy behavior).
        'object': returns the raw pyvista plotter object.
    export_path : str, optional
        If provided, saves the final figure to this path (e.g., 'figure.png').
        With `plot_regions_separately`, it is instead the directory that the
        per-region PNGs are saved to.
    custom_atlas_proc : dict, optional
        Parameters for processing custom GIfTI files.
        Keys: 'smooth_i' (iterations) and 'smooth_f' (relaxation factor).
        Default is {'smooth_i': 15, 'smooth_f': 0.6}.
    atlas_color_seed : int, optional
        Seed controlling the categorical color arrangement in atlas (no-data) mode.
        With the default palette it seeds the distinct-color generator; with a
        colormap it seeds a shuffle so gradient-adjacent regions get contrasting
        colors. Change it to get a different, reproducible arrangement. Ignored when
        `data` is given. Default is 42.
    plot_regions_separately : bool, optional
        If True, renders each region + view combination on its own instead of a single
        combined figure. If ``export_path`` is set, it is always treated as a directory
        (created if missing): one transparent-background PNG per region + view is saved
        there (named ``{region}_{view_face}.png``, useful for SVG tracing pipelines)
        and None is returned. ``view_face`` is the view name without ``left_``/``right_``;
        midline regions keep the full view name. Otherwise one matplotlib figure per
        region + view is opened and the axes are returned as a list.
        All renders share the same camera framing, so regions keep their relative
        position and size, and the same size: `figsize` if given, else 3.5 x 3 inches.
        `ax`, `layout`, `display_type` and `cbar_kwargs` are not used in this mode and
        no colorbar is drawn. Default is False.
    shared_hemisphere_colors : bool, optional
        If True, bilateral region pairs (e.g. ``putamen_l`` / ``putamen_r``) are drawn
        in the same color, so each structure reads as one color across both hemispheres.
        Pairs are matched by name after removing one hemisphere tag (case-insensitive):
        a ``_l``/``_r`` or ``-lh``/``-rh`` suffix, or a ``l-``/``r-``, ``l_``/``r_``,
        ``left_``/``right_`` or ``left-``/``right-`` prefix. Regions named in any other
        way keep their own color.
        Only applies in atlas (no-data) mode; ignored when `data` is given. If False
        (default), every region is assigned its own independent color.

    Returns
    -------
    matplotlib.axes.Axes or pyvista.Plotter or IPython.display.DisplayObject
        returns based on display_type:
        - 'matplotlib': returns a matplotlib axes object.
        - 'interactive': returns a trame browser viewer.
        - 'pyvista': returns a static jupyter widget.
        - 'object': returns the raw pyvista plotter.
        with `plot_regions_separately`, returns None if `export_path` is set,
        otherwise a list of matplotlib axes (one per region + view).
    """

    # defaults
    if atlas is None and custom_atlas_path is None:
        atlas = 'aseg'

    # load context brain mesh (if requested) or accept mesh directly
    ctx_meshes = load_bmesh(bmesh)

    # load regional atlas meshes
    # resolve atlas path (either download or custom directory)
    atlas_dir = _resolve_resource_path(atlas, 'subcortical', custom_path=custom_atlas_path)

    # locate mesh files, returns dict: {'Left_Thalamus': '/path/to/Left_Thalamus.vtk', ...}
    file_map = _find_subcortical_files(atlas_dir)
    rmesh_names = get_atlas_regions(atlas, 'subcortical', custom_atlas_path)

    # load meshes from cache or disk
    meshes = {}
    cache_key = 'custom' if custom_atlas_path else atlas
    for name, fpath in file_map.items():
        mesh = _retrieve_static_mesh('subcortical', cache_key, name, fpath, **custom_atlas_proc)
        if mesh:
            meshes[name] = mesh

    # prepare colors and map data
    if data is not None:
        cmap = cmap if cmap is not None else 'coolwarm'
        d_data = prep_data(data, rmesh_names, atlas, 'subcortical')
        valid_vals = [v for v in d_data.values() if pd.notna(v)]
        vmin = vminmax[0] if vminmax[0] is not None else (min(valid_vals) if valid_vals else 0)
        vmax = vminmax[1] if vminmax[1] is not None else (max(valid_vals) if valid_vals else 1)
        c_vlim = [vmin, vmax]
    else:
        # determine the key for each region: base name (hemisphere-shared) or the raw name
        color_keys = (
            list(dict.fromkeys(get_base_name(n) for n in rmesh_names))
            if shared_hemisphere_colors
            else list(dict.fromkeys(rmesh_names))
        )

        # generate one color per unique key
        if cmap is None:
            key_colors = generate_distinct_colors(len(color_keys), seed=atlas_color_seed)
        else:
            # get_cmap accepts either a colormap name (str) or a Colormap object
            cmap_obj = get_cmap(cmap)
            key_colors = [tuple(c[:3]) for c in cmap_obj(np.linspace(0, 1, len(color_keys)))]
            random.Random(atlas_color_seed).shuffle(key_colors)
        color_map = dict(zip(color_keys, key_colors))

        lookup = get_base_name if shared_hemisphere_colors else (lambda n: n)
        d_atlas_colors = {name: color_map[lookup(name)] for name in rmesh_names}
        c_vlim = [0, 1]

    # setup views and shading (shared by both code paths)
    sel_views = get_view_configs(views)

    # get shading parameters from style
    shading_params = get_shading_preset(style)

    if plot_regions_separately:
        # per-region output; export_path is always a directory here
        do_export = export_path is not None
        if do_export:
            out_dir = export_path
            os.makedirs(out_dir, exist_ok=True)

        # every render has the same size. 'object' makes prepare_plotter only convert
        # figsize to pixels, so no figure is created for the unused combined layout
        _, _, region_size = prepare_plotter(None, 'object', sel_views, layout, figsize)
        region_window_size = list(region_size) if region_size is not None else [700, 600]
        region_axes = []

        for view_name, cfg in sel_views.items():
            print(f"Rendering view: {view_name}...")

            for target_name in list(meshes.keys()):
                is_left, is_right = _get_side_tokens(target_name)
                if cfg['side'] == 'L' and is_right and not is_left:
                    continue
                if cfg['side'] == 'R' and is_left and not is_right:
                    continue

                if is_left != is_right:
                    view_face = view_name.replace('left_', '').replace('right_', '')
                else:
                    view_face = view_name

                indiv_plotter = pv.Plotter(off_screen=True, window_size=region_window_size)
                indiv_plotter.set_background('white')
                add_context_to_view(indiv_plotter, ctx_meshes, cfg['side'], bmesh_alpha,
                                    bmesh_color, **shading_params)

                region_actors = {}
                for name, mesh in meshes.items():
                    n_is_left, n_is_right = _get_side_tokens(name)
                    if cfg['side'] == 'L' and n_is_right and not n_is_left:
                        continue
                    if cfg['side'] == 'R' and n_is_left and not n_is_right:
                        continue

                    props = shading_params.copy()
                    if data is not None:
                        val = d_data.get(name, np.nan) if pd.notna(d_data.get(name)) else np.nan
                        has_val = not np.isnan(val)
                        mesh['Data'] = np.full(mesh.n_points, val)
                        props.update({
                            'scalars': 'Data', 'cmap': cmap, 'clim': c_vlim,
                            'nan_color': nan_color, 'opacity': 1.0 if has_val else nan_alpha,
                            'show_scalar_bar': False,
                        })
                    else:
                        props.update({'color': d_atlas_colors[name], 'opacity': 1.0})

                    region_actors[name] = indiv_plotter.add_mesh(mesh, **props)

                # frame the camera on all regions before hiding the non-targets, so each
                # region keeps its true position and size (hidden actors are not framed)
                set_camera(indiv_plotter, cfg, zoom=zoom)
                for name, actor in region_actors.items():
                    actor.SetVisibility(name == target_name)
                indiv_plotter.hide_axes()

                if do_export:
                    out_file = os.path.join(out_dir, f'{target_name}_{view_face}.png')
                    indiv_plotter.screenshot(out_file, transparent_background=True)
                    indiv_plotter.close()
                    print(f"  Saved → {out_file}")
                else:
                    img = indiv_plotter.screenshot(transparent_background=True, return_img=True)
                    indiv_plotter.close()
                    _, region_ax = plt.subplots()
                    region_ax.imshow(img)
                    region_ax.set_title(f'{target_name} ({view_name})', fontsize=8)
                    region_ax.axis('off')
                    region_axes.append(region_ax)

        return None if do_export else region_axes

    # setup plotter (combined / normal path)
    ax, display_type, figsize = prepare_plotter(ax, display_type, sel_views, layout, figsize)
    needs_bottom = (data is not None)
    plotter, ncols, nrows = setup_plotter(sel_views, layout, figsize, display_type,
                                          needs_bottom_row=needs_bottom)
    scalar_bar_mapper = None

    # pre-calculate side tokens for all meshes to avoid regex in loops
    side_info = {n: _get_side_tokens(n) for n in meshes.keys()}

    # plotting loop
    for i, (view_name, cfg) in enumerate(sel_views.items()):
        plotter.subplot(i // ncols, i % ncols)

        # add context (uses style kwargs for consistent lighting)
        add_context_to_view(plotter, ctx_meshes, cfg['side'], bmesh_alpha, bmesh_color,
                            **shading_params)

        # add regions
        for name, mesh in meshes.items():
            # side filtering using pre-calculated tokens
            is_left, is_right = side_info[name]
            if cfg['side'] == 'L' and is_right and not is_left: continue
            if cfg['side'] == 'R' and is_left and not is_right: continue

            # determine properties for this mesh
            props = shading_params.copy()

            if data is not None:
                val = d_data.get(name, np.nan) if pd.notna(d_data.get(name)) else np.nan
                has_val = not np.isnan(val)

                mesh['Data'] = np.full(mesh.n_points, val)

                props.update({
                    'scalars': 'Data', 'cmap': cmap, 'clim': c_vlim,
                    'nan_color': nan_color, 'opacity': 1.0 if has_val else nan_alpha,
                    'show_scalar_bar': False
                })
            else:
                color = d_atlas_colors[name]
                props.update({'color': color, 'opacity': 1.0})

            actor = plotter.add_mesh(mesh, **props)

            if data is not None and scalar_bar_mapper is None and 'scalars' in props:
                 scalar_bar_mapper = actor.mapper

        set_camera(plotter, cfg, zoom=zoom)
        plotter.hide_axes()

    # colorbar
    cbar_info = []
    if needs_bottom and scalar_bar_mapper:
        if display_type != 'matplotlib':
            add_colorbars(plotter, [scalar_bar_mapper], [''], nrows, figsize)
        else:
            cbar_info.append({'cmap': cmap, 'vminmax': c_vlim})

    return finalize_plot(plotter, export_path, display_type, ax=ax, cbar_info=cbar_info, cbar_kwargs=cbar_kwargs)

yabplot.plotting.plot_tracts(data=None, atlas=None, custom_atlas_path=None, ax=None, cbar_kwargs=None, views=None, layout=None, figsize=None, cmap='coolwarm', alpha=1.0, vminmax=[None, None], nan_color='#BDBDBD', nan_alpha=1.0, style='default', bmesh='midthickness', bmesh_alpha=0.15, bmesh_color='lightgray', zoom=1.2, orientation_coloring=False, display_type='matplotlib', tract_kwargs=dict(render_lines_as_tubes=True, line_width=1.2), export_path=None)

Visualize data on the white matter tractography bundles using a specified atlas.

Renders streamlines from .trk files. Can color tracts by scalar values, categorically, or by local fiber orientation.

Parameters:

Name Type Description Default
data (dict, list, ndarray, Series, DataFrame)

Scalar values for each tract, or mrtrix3 derived .tsf file path for each tract. If dict: Keys must match tract names. If array/list: Must strictly match the sorted list of tracts in the atlas. If None: Tracts are colored by category (distinct colors) or orientation.

None
atlas str

Name of the standard tract atlas (e.g., 'hcp1065_small', see 'yabplot.get_available_resources' for more). Defaults to 'xtract_tiny'.

None
custom_atlas_path str

Path to a local directory containing .trk files for each tract.

None
views list of str

Views to display. Can be a list of presets ('left_lateral', 'right_medial', etc.) or a dictionary of camera configurations. Defaults to all views.

None
layout tuple(rows, cols)

Grid layout for subplots. If None, automatically calculated based on the number of views.

None
figsize tuple(width, height)

Window size in inches. If None, automatically calculated based on the number of views and layout.

None
cmap str or Colormap

Colormap for continuous data. Ignored if data is None. Default is 'coolwarm'.

'coolwarm'
alpha float

Opacity of the tracts (0.0 to 1.0).

1.0
vminmax list[min, max]

Manual lower and upper bounds for the colormap. If [None, None], bounds are inferred from the data range.

[None, None]
nan_color str

Color for tracts with missing data (NaN). Default is grey '#BDBDBD'.

'#BDBDBD'
nan_alpha float

Opacity (0.0 to 1.0) for regions with no data. Set to 0.0 to hide them.

1.0
style str

Lighting preset ('default', 'matte', 'glossy', 'sculpted', 'flat').

'default'
bmesh PolyData or dict

Configure background context brain mesh. Accepts a string (e.g., 'midthickness', 'white', 'swm', etc), single PolyData (used for both hemispheres) or a dict with 'L'/'R' keys. Default is 'midthickness'.

'midthickness'
bmesh_alpha float

Opacity of the context brain mesh. Default is 0.15.

0.15
bmesh_color str

Color of the context brain mesh.

'lightgray'
zoom float

Camera zoom level. >1.0 zooms in, <1.0 zooms out. Default is 1.2.

1.2
orientation_coloring bool

If True, ignores data and colors fibers based on their local directional orientation (Red=L/R, Green=A/P, Blue=S/I).

False
tract_kwargs dict

Additional arguments passed to PyVista's add_mesh. Default configures tubes: {'render_lines_as_tubes': True, 'line_width': 1.2}.

dict(render_lines_as_tubes=True, line_width=1.2)
display_type (matplotlib, interactive, pyvista, object)

'matplotlib': returns a matplotlib figure and axis (default). 'interactive': opens an interactive trame viewer in the browser. 'pyvista': returns a static jupyter widget (legacy behavior). 'object': returns the raw pyvista plotter object.

'matplotlib'
export_path str

If provided, saves the final figure to this path (e.g., 'figure.png').

None

Returns:

Type Description
Axes or Plotter or DisplayObject

returns based on display_type: - 'matplotlib': returns a matplotlib axes object. - 'interactive': returns a trame browser viewer. - 'pyvista': returns a static jupyter widget. - 'object': returns the raw pyvista plotter.

Source code in yabplot/plotting.py
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
def plot_tracts(data=None, atlas=None, custom_atlas_path=None, ax=None, cbar_kwargs=None, views=None, layout=None,
                figsize=None, cmap='coolwarm', alpha=1.0, vminmax=[None, None],
                nan_color='#BDBDBD', nan_alpha=1.0, style='default',
                bmesh='midthickness', bmesh_alpha=0.15, bmesh_color='lightgray',
                zoom=1.2, orientation_coloring=False, display_type='matplotlib',
                tract_kwargs=dict(render_lines_as_tubes=True, line_width=1.2),
                export_path=None):
    """
    Visualize data on the white matter tractography bundles using a specified atlas.

    Renders streamlines from .trk files. Can color tracts by scalar values,
    categorically, or by local fiber orientation.

    Parameters
    ----------
    data : dict, list, numpy.ndarray, pandas.Series, pandas.DataFrame, optional
        Scalar values for each tract, or mrtrix3 derived .tsf file path for each tract.
        If dict: Keys must match tract names.
        If array/list: Must strictly match the sorted list of tracts in the atlas.
        If None: Tracts are colored by category (distinct colors) or orientation.
    atlas : str, optional
        Name of the standard tract atlas (e.g., 'hcp1065_small',
        see 'yabplot.get_available_resources' for more).
        Defaults to 'xtract_tiny'.
    custom_atlas_path : str, optional
        Path to a local directory containing .trk files for each tract.
    views : list of str, optional
        Views to display. Can be a list of presets ('left_lateral', 'right_medial', etc.)
        or a dictionary of camera configurations. Defaults to all views.
    layout : tuple (rows, cols), optional
        Grid layout for subplots. If None, automatically calculated based on the number of views.
    figsize : tuple (width, height), optional
        Window size in inches. If None, automatically calculated based on the number of views and layout.
    cmap : str or matplotlib.colors.Colormap, optional
        Colormap for continuous data. Ignored if `data` is None. Default is 'coolwarm'.
    alpha : float, optional
        Opacity of the tracts (0.0 to 1.0).
    vminmax : list [min, max], optional
        Manual lower and upper bounds for the colormap. If [None, None],
        bounds are inferred from the data range.
    nan_color : str, optional
        Color for tracts with missing data (NaN). Default is grey '#BDBDBD'.
    nan_alpha : float, optional
        Opacity (0.0 to 1.0) for regions with no data. Set to 0.0 to hide them.
    style : str, optional
        Lighting preset ('default', 'matte', 'glossy', 'sculpted', 'flat').
    bmesh : pyvista.PolyData or dict, optional
        Configure background context brain mesh. Accepts a string
        (e.g., 'midthickness', 'white', 'swm', etc), single PolyData (used for both hemispheres)
        or a dict with 'L'/'R' keys. Default is 'midthickness'.
    bmesh_alpha : float, optional
        Opacity of the context brain mesh. Default is 0.15.
    bmesh_color : str, optional
        Color of the context brain mesh.
    zoom : float, optional
        Camera zoom level. >1.0 zooms in, <1.0 zooms out. Default is 1.2.
    orientation_coloring : bool, optional
        If True, ignores `data` and colors fibers based on their local directional
        orientation (Red=L/R, Green=A/P, Blue=S/I).
    tract_kwargs : dict, optional
        Additional arguments passed to PyVista's `add_mesh`.
        Default configures tubes: `{'render_lines_as_tubes': True, 'line_width': 1.2}`.
    display_type : {'matplotlib', 'interactive', 'pyvista', 'object'}, optional
        'matplotlib': returns a matplotlib figure and axis (default).
        'interactive': opens an interactive trame viewer in the browser.
        'pyvista': returns a static jupyter widget (legacy behavior).
        'object': returns the raw pyvista plotter object.
    export_path : str, optional
        If provided, saves the final figure to this path (e.g., 'figure.png').

    Returns
    -------
    matplotlib.axes.Axes or pyvista.Plotter or IPython.display.DisplayObject
        returns based on display_type:
        - 'matplotlib': returns a matplotlib axes object.
        - 'interactive': returns a trame browser viewer.
        - 'pyvista': returns a static jupyter widget.
        - 'object': returns the raw pyvista plotter.
    """

    # defaults
    if atlas is None and custom_atlas_path is None:
        atlas = 'xtract_tiny'

    # resolve atlas path (either download or custom directory)
    atlas_dir = _resolve_resource_path(atlas, 'tracts', custom_path=custom_atlas_path)

    # locate tract files, returns dict eg {'CST_L': '/path/to/CST_L.trk', ...}
    file_map = _find_tract_files(atlas_dir)
    tract_names = get_atlas_regions(atlas, 'tracts', custom_atlas_path)

    # prepare colors and map data
    if data is not None:
        d_data = prep_data(data, tract_names, atlas, 'tracts')
        all_vals = []
        for v in d_data.values():
            v_arr = np.atleast_1d(v)
            all_vals.append(v_arr[~np.isnan(v_arr)])

        if all_vals:
            valid_vals = np.concatenate(all_vals)
            vmin = vminmax[0] if vminmax[0] is not None else (np.min(valid_vals) if len(valid_vals) else 0)
            vmax = vminmax[1] if vminmax[1] is not None else (np.max(valid_vals) if len(valid_vals) else 1)
        else:
            vmin, vmax = 0, 1
        c_vlim = [vmin, vmax]
    # categorical/orientation mode
    else:
        colors = generate_distinct_colors(len(tract_names), seed=42)
        d_atlas_colors = {name: color for name, color in zip(tract_names, colors)}
        c_vlim = [0, 1]

    # load context brain mesh (if requested)
    ctx_meshes = load_bmesh(bmesh)

    # setup plotter
    sel_views = get_view_configs(views)
    ax, display_type, figsize = prepare_plotter(ax, display_type, sel_views, layout, figsize)

    needs_bottom = (data is not None and not orientation_coloring)
    plotter, ncols, nrows = setup_plotter(sel_views, layout, figsize, display_type,
                                           needs_bottom_row=needs_bottom)
    plotter.enable_depth_peeling(number_of_peels=10)
    plotter.enable_anti_aliasing('msaa') # smooth lines
    shading_params = get_shading_preset(style)
    scalar_bar_mapper = None

    # pre-calculate side tokens for all tracts to avoid regex in loops

    side_info = {n: _get_side_tokens(n) for n in tract_names}

    # plotting
    cache_key = 'custom' if custom_atlas_path else atlas
    for i, (view_name, cfg) in enumerate(sel_views.items()):
        plotter.subplot(i // ncols, i % ncols)

        # add context (passed shading params to context mesh)
        add_context_to_view(plotter, ctx_meshes, cfg['side'], bmesh_alpha, bmesh_color, **shading_params)

        # add tracts
        for name in tract_names:
            # optimization: early exit for hidden tracts
            has_value = False
            val = np.nan

            if data is not None and not orientation_coloring:
                # check data
                if name in d_data and d_data[name] is not None:
                    val = d_data[name]
                    if np.isscalar(val) and np.isnan(val):
                        has_value = False
                    elif not np.isscalar(val) and np.all(np.isnan(val)):
                        has_value = False
                    else:
                        has_value = True
                else:
                    has_value = False

                if not has_value and nan_alpha == 0:
                    continue

            # side filtering using pre-calculated tokens
            is_left, is_right = side_info[name]
            if cfg['side'] == 'L' and is_right and not is_left: continue
            if cfg['side'] == 'R' and is_left and not is_right: continue

            # load mesh from lru cache
            fpath = file_map.get(name)
            if not fpath: continue
            base_mesh = _retrieve_static_mesh('tracts', cache_key, name, fpath)
            if base_mesh is None: continue

            pv_mesh = base_mesh.copy(deep=False)
            # start with style presets, then override with tract_kwargs and dynamic props
            props = shading_params.copy()
            props.update(tract_kwargs)

            if orientation_coloring:
                pv_mesh['Data'] = pv_mesh.point_data['tangents']

                props.update({
                    'scalars': 'Data', 'rgb': True, 'opacity': alpha
                })

            elif data is not None:
                if np.isscalar(val):
                    pv_mesh['Data'] = np.full(pv_mesh.n_points, val)
                elif len(val) == 1:
                    pv_mesh['Data'] = np.full(pv_mesh.n_points, val[0])
                elif len(val) == pv_mesh.n_points:
                    pv_mesh['Data'] = val
                else:
                    raise ValueError(
                        f"Data shape mismatch for tract '{name}'. Must be a scalar "
                        f"or a 1D array matching the number of points. "
                        f"Array shape: {np.shape(val)}, mesh points: {pv_mesh.n_points}"
                    )

                current_opacity = alpha if has_value else nan_alpha

                props.update({
                    'scalars': 'Data', 'cmap': cmap, 'clim': c_vlim,
                    'nan_color': nan_color, 'opacity': current_opacity, 'show_scalar_bar': False
                })

            else:
                color = d_atlas_colors[name]
                props.update({
                    'color': color, 'opacity': alpha
                })

            actor = plotter.add_mesh(pv_mesh, **props)

            if data is not None and not orientation_coloring and scalar_bar_mapper is None and 'scalars' in props:
                scalar_bar_mapper = actor.mapper

        set_camera(plotter, cfg, zoom=zoom, distance=150)
        plotter.hide_axes()

    # colorbar
    cbar_info = []
    if needs_bottom and scalar_bar_mapper:
        if display_type != 'matplotlib':
            add_colorbars(plotter, [scalar_bar_mapper], [''], nrows, figsize)
        else:
            cbar_info.append({'cmap': cmap, 'vminmax': c_vlim})

    # finalize
    ret_val = finalize_plot(plotter, export_path, display_type, ax=ax, cbar_info=cbar_info, cbar_kwargs=cbar_kwargs)

    if display_type != 'interactive':
        del plotter
        gc.collect()

    return ret_val

yabplot.plotting.plot_voxelwise(nii_path, threshold='95%', n_levels=20, ax=None, cbar_kwargs=None, views=None, layout=None, figsize=None, cmap='coolwarm', vminmax=[None, None], blur_sigma=0.0, smooth_i=0, smooth_f=0.0, style='default', bmesh='midthickness', bmesh_alpha=0.15, bmesh_color='lightgray', ignore_bmesh=True, zoom=1.2, display_type='matplotlib', export_path=None)

Visualize 3D voxelwise data from a NIfTI file by extracting it as surface meshes.

This function extracts topographical shells (isosurfaces) from a volumetric image and renders them within a transparent brain mesh and makes the high-intensity layers with higher priority and more visible.

Parameters:

Name Type Description Default
nii_path str

Path to the NIfTI file to visualize.

required
threshold float or str

Value below which voxels are hidden. Can be a float or a percentage string like '95%'. Default is '95%'.

'95%'
n_levels int

Number of nested isosurfaces to generate. Higher values show more detail of the internal intensity gradient. Default is 20.

20
ax Axes

Matplotlib axis to render into if display_type is 'matplotlib'.

None
cbar_kwargs dict

Arguments passed to the colorbar.

None
views list of str

Views to display (e.g. 'left_lateral', 'superior'). Defaults to all views.

None
layout tuple(rows, cols)

Grid layout for subplots. If None, auto-calculated.

None
figsize tuple(width, height)

Window size in inches.

None
cmap str or Colormap

Colormap for the continuous voxel data.

'coolwarm'
vminmax list[min, max]

Colormap bounds. If [None, None], uses robust 1st/99th percentiles.

[None, None]
blur_sigma float

Gaussian blur (voxel units) applied before thresholding for smoother geometry.

0.0
smooth_i int

Number of Laplacian smoothing iterations for the extracted mesh.

0
smooth_f float

Relaxation factor for mesh smoothing.

0.0
style str

Lighting preset ('default', 'matte', 'glossy', 'sculpted', 'flat').

'default'
bmesh str, dict, or pyvista.PolyData

Background context brain mesh. Accepts the name of a built-in mesh (e.g. 'midthickness', 'pial'; see get_available_resources('bmesh')), a single PolyData, a dict with 'L'/'R' keys, or None to hide it. The built-in meshes are in MNI152NLin6Asym space (see Notes). Default is 'midthickness'.

'midthickness'
bmesh_alpha float

Opacity of the context brain mesh. Default is 0.15.

0.15
bmesh_color str

Color of the context brain mesh.

'lightgray'
ignore_bmesh bool

If True (default), data renders on top of brain regardless of depth (X-ray). If False, brain surface correctly obscures the internal data.

True
zoom float

Camera zoom level. Default is 1.2.

1.2
display_type (matplotlib, interactive, pyvista, object)

Rendering backend and return type. Default is 'matplotlib'.

'matplotlib'
export_path str

If provided, saves the final figure to this path.

None

Returns:

Type Description
Axes or Plotter or DisplayObject

returns based on display_type: - 'matplotlib': returns a matplotlib axes object. - 'interactive': returns a trame browser viewer. - 'pyvista': returns a static jupyter widget. - 'object': returns the raw pyvista plotter object.

Notes

The volume is placed using the affine stored in the NIfTI header. It is not resampled or registered, so it can be in any space, but it only lines up with the context brain if both are in the same space.

The built-in meshes are group-average cortical surfaces from the Human Connectome Project (fs_LR 32k) in MNI152NLin6Asym space, without cerebellum or brainstem. For data in another space (e.g. MNI152NLin2009cAsym from fMRIPrep, or a subject's native space), build a matching context brain with load_nii_as_mesh, for instance from a brain mask, and pass it as bmesh.

Source code in yabplot/plotting.py
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
def plot_voxelwise(nii_path, threshold='95%', n_levels=20, ax=None, cbar_kwargs=None, 
                   views=None, layout=None, figsize=None, cmap='coolwarm', 
                   vminmax=[None, None], blur_sigma=0.0, smooth_i=0, smooth_f=0.0,
                   style='default', bmesh='midthickness', bmesh_alpha=0.15, 
                   bmesh_color='lightgray', ignore_bmesh=True, zoom=1.2, 
                   display_type='matplotlib', export_path=None):
    """
    Visualize 3D voxelwise data from a NIfTI file by extracting it as surface meshes.

    This function extracts topographical shells (isosurfaces) from a volumetric image
    and renders them within a transparent brain mesh and makes the high-intensity
    layers with higher priority and more visible.

    Parameters
    ----------
    nii_path : str
        Path to the NIfTI file to visualize.
    threshold : float or str, optional
        Value below which voxels are hidden. Can be a float or a percentage
        string like '95%'. Default is '95%'.
    n_levels : int, optional
        Number of nested isosurfaces to generate. Higher values show more detail
        of the internal intensity gradient. Default is 20.
    ax : matplotlib.axes.Axes, optional
        Matplotlib axis to render into if display_type is 'matplotlib'.
    cbar_kwargs : dict, optional
        Arguments passed to the colorbar.
    views : list of str, optional
        Views to display (e.g. 'left_lateral', 'superior'). Defaults to all views.
    layout : tuple (rows, cols), optional
        Grid layout for subplots. If None, auto-calculated.
    figsize : tuple (width, height), optional
        Window size in inches.
    cmap : str or matplotlib.colors.Colormap, optional
        Colormap for the continuous voxel data.
    vminmax : list [min, max], optional
        Colormap bounds. If [None, None], uses robust 1st/99th percentiles.
    blur_sigma : float, optional
        Gaussian blur (voxel units) applied before thresholding for smoother geometry.
    smooth_i : int, optional
        Number of Laplacian smoothing iterations for the extracted mesh.
    smooth_f : float, optional
        Relaxation factor for mesh smoothing.
    style : str, optional
        Lighting preset ('default', 'matte', 'glossy', 'sculpted', 'flat').
    bmesh : str, dict, or pyvista.PolyData, optional
        Background context brain mesh. Accepts the name of a built-in mesh
        (e.g. 'midthickness', 'pial'; see `get_available_resources('bmesh')`),
        a single PolyData, a dict with 'L'/'R' keys, or None to hide it.
        The built-in meshes are in MNI152NLin6Asym space (see Notes).
        Default is 'midthickness'.
    bmesh_alpha : float, optional
        Opacity of the context brain mesh. Default is 0.15.
    bmesh_color : str, optional
        Color of the context brain mesh.
    ignore_bmesh : bool, optional
        If True (default), data renders on top of brain regardless of depth (X-ray).
        If False, brain surface correctly obscures the internal data.
    zoom : float, optional
        Camera zoom level. Default is 1.2.
    display_type : {'matplotlib', 'interactive', 'pyvista', 'object'}, optional
        Rendering backend and return type. Default is 'matplotlib'.
    export_path : str, optional
        If provided, saves the final figure to this path.

    Returns
    -------
    matplotlib.axes.Axes or pyvista.Plotter or IPython.display.DisplayObject
        returns based on display_type:
        - 'matplotlib': returns a matplotlib axes object.
        - 'interactive': returns a trame browser viewer.
        - 'pyvista': returns a static jupyter widget.
        - 'object': returns the raw pyvista plotter object.

    Notes
    -----
    The volume is placed using the affine stored in the NIfTI header. It is not
    resampled or registered, so it can be in any space, but it only lines up with
    the context brain if both are in the same space.

    The built-in meshes are group-average cortical surfaces from the Human
    Connectome Project (fs_LR 32k) in MNI152NLin6Asym space, without cerebellum
    or brainstem. For data in another space (e.g. MNI152NLin2009cAsym from
    fMRIPrep, or a subject's native space), build a matching context brain with
    `load_nii_as_mesh`, for instance from a brain mask, and pass it as `bmesh`.
    """

    # load and validate data
    img = nib.load(nii_path)
    data = img.get_fdata()

    if data.ndim > 3:
        warnings.warn(f"[WARNING] detected {data.ndim}d nifti volume. using the first volume (index 0).")
        data = data[..., 0]

    data = np.nan_to_num(data, nan=0.0)

    # resolve threshold
    if isinstance(threshold, str) and threshold.endswith('%'):
        perc = float(threshold.strip('%'))
        valid_vals = np.abs(data[data != 0.0])
        actual_threshold = np.percentile(valid_vals, perc) if valid_vals.size > 0 else 1e-6
    else:
        actual_threshold = float(threshold) if threshold is not None else 1e-6

    # resolve color limits
    valid_original_mask = (np.abs(data) >= actual_threshold)
    if np.any(valid_original_mask):
        surviving = data[valid_original_mask]
        has_negative = np.any(surviving < -actual_threshold)

        if has_negative:
            limit = max(np.percentile(np.abs(surviving), 99), actual_threshold * 1.1)
            vmin_auto, vmax_auto = -limit, limit
        else:
            vmin_auto = np.percentile(surviving, 1)
            vmax_auto = np.percentile(surviving, 99)

        if vmin_auto == vmax_auto:
            vmin_auto, vmax_auto = np.min(surviving), np.max(surviving)
    else:
        raise ValueError(f"No voxels found above threshold {actual_threshold}.")

    vmin = vminmax[0] if vminmax[0] is not None else vmin_auto
    vmax = vminmax[1] if vminmax[1] is not None else vmax_auto

    # mesh extraction via nested isosurfaces
    data_to_contour = gaussian_filter(data, sigma=float(blur_sigma)) if blur_sigma > 0 else data
    grid = pv.ImageData()
    grid.dimensions = data.shape
    grid.point_data['Data'] = data_to_contour.flatten(order='F')

    # generate levels for both positive and negative (if applicable)
    pos_levels = np.linspace(actual_threshold, vmax, int(n_levels)) if vmax > actual_threshold else []
    neg_levels = np.linspace(-actual_threshold, vmin, int(n_levels)) if vmin < -actual_threshold else []
    shell_meshes = [] # List of (mesh, level_value)
    for val in pos_levels:
        mesh = grid.contour(isosurfaces=[val], scalars='Data')
        if mesh.n_points > 0:
            mesh.transform(img.affine, inplace=True)
            if smooth_i and smooth_i > 0:
                mesh = mesh.smooth(n_iter=int(smooth_i), relaxation_factor=float(smooth_f))
            shell_meshes.append((mesh, val))
    for val in neg_levels:
        mesh = grid.contour(isosurfaces=[val], scalars='Data')
        if mesh.n_points > 0:
            mesh.transform(img.affine, inplace=True)
            if smooth_i and smooth_i > 0:
                mesh = mesh.smooth(n_iter=int(smooth_i), relaxation_factor=float(smooth_f))
            shell_meshes.append((mesh, val))

    if not shell_meshes:
        raise ValueError("Extracted mesh has no vertices. Adjust threshold or blur_sigma.")

    # plotter setup
    sel_views = get_view_configs(views)
    ax, display_type, figsize = prepare_plotter(ax, display_type, sel_views, layout, figsize)

    plotter, ncols, nrows = setup_plotter(sel_views, layout, figsize, display_type, needs_bottom_row=True)
    plotter.enable_depth_peeling(number_of_peels=20)
    plotter.enable_anti_aliasing('msaa')
    shading_params = get_shading_preset(style)
    scalar_bar_mapper = None

    # load context brain mesh
    ctx_meshes = load_bmesh(bmesh)

    # rendering loop
    for i, (view_name, cfg) in enumerate(sel_views.items()):
        plotter.subplot(i // ncols, i % ncols)

        # base depth offset: push entire voxel group relative to brain
        voxel_group_base = -20000.0 if ignore_bmesh else 20000.0

        # helper to add shells from low to peak intensity
        # adding cores last ensures peak visibility in painter's algorithm
        def add_voxel_data():
            nonlocal scalar_bar_mapper
            sorted_shells = sorted(shell_meshes, key=lambda x: abs(x[1]))
            for s_idx, (mesh, val) in enumerate(sorted_shells):
                # hemisphere filtering
                m_plot = mesh
                if cfg['side'] == 'L':
                    m_plot = mesh.clip(normal='x', origin=(0,0,0), invert=True)
                elif cfg['side'] == 'R':
                    m_plot = mesh.clip(normal='x', origin=(0,0,0), invert=False)

                if m_plot.n_points == 0: continue

                actor = plotter.add_mesh(
                    m_plot, scalars='Data', cmap=cmap, clim=(vmin, vmax),
                    opacity=1.0, show_scalar_bar=False, smooth_shading=True,
                    lighting=False, name=f"voxels_{i}_{s_idx}"
                )

                # higher priority = closer to the camera, so peak cores are always on top
                local_priority = voxel_group_base - (100.0 * (s_idx + 1))
                actor.mapper.SetResolveCoincidentTopologyToPolygonOffset()
                actor.mapper.SetRelativeCoincidentTopologyPolygonOffsetParameters(local_priority, local_priority)

                if scalar_bar_mapper is None:
                    scalar_bar_mapper = actor.mapper

        def add_brain():
            if not ctx_meshes: return
            for h, mesh in ctx_meshes.items():
                if (cfg['side'] == 'L' and h == 'R') or (cfg['side'] == 'R' and h == 'L'): continue
                actor = plotter.add_mesh(mesh, color=bmesh_color, opacity=bmesh_alpha,
                                         smooth_shading=True, show_edges=False,
                                         name=f"bmesh_{h}_{i}", **shading_params)
                actor.mapper.SetResolveCoincidentTopologyToPolygonOffset()
                actor.mapper.SetRelativeCoincidentTopologyPolygonOffsetParameters(0.0, 0.0)

        # relative addition order
        if ignore_bmesh:
            add_brain()
            add_voxel_data()
        else:
            add_voxel_data()
            add_brain()

        set_camera(plotter, cfg, zoom=zoom)
        plotter.hide_axes()

    # colorbar setup
    cbar_title = "voxel values"
    cbar_info = []
    if scalar_bar_mapper:
        if display_type != 'matplotlib':
            add_colorbars(plotter, [scalar_bar_mapper], [cbar_title], nrows, figsize)
        else:
            cbar_info.append({'cmap': cmap, 'vminmax': [vmin, vmax], 'title': cbar_title})

    return finalize_plot(plotter, export_path, display_type, ax=ax, cbar_info=cbar_info, cbar_kwargs=cbar_kwargs)

yabplot.plotting.plot_vertexwise(lh, rh, scalars='Data', ax=None, cbar_kwargs=None, views=None, layout=None, figsize=None, cmap='coolwarm', vminmax=[None, None], nan_color=(1.0, 1.0, 1.0), style='default', zoom=1.2, display_type='matplotlib', export_path=None, lut=None, proc_vertices='sharp')

Visualize arbitrary per-vertex scalar data on a user-supplied brain mesh.

Unlike plot_cortical, this function requires no atlas. The user provides PyVista PolyData meshes with per-vertex scalar data stored under the key specified by scalars.

Parameters:

Name Type Description Default
lh PolyData

Left hemisphere mesh containing a (N,) float array under lh[scalars].

required
rh PolyData

Right hemisphere mesh containing a (N,) float array under rh[scalars].

required
scalars str

The string key corresponding to the scalar data array in the PyVista point data dictionary. Default is 'Data'.

'Data'
views list of str

Can be a list of presets ('left_lateral', 'right_medial', etc.) or a dictionary of camera configurations. Defaults to all views.

None
layout tuple(rows, cols)

Grid layout for subplots. If None, auto-calculated.

None
figsize tuple(width, height)

Window size in inches. If None, automatically calculated based on the number of views and layout.

None
cmap str or Colormap

Colormap. Default is 'coolwarm'.

'coolwarm'
vminmax list[min, max]

Colormap bounds. If [None, None], inferred from data range.

[None, None]
nan_color tuple or str

Color for NaN vertices. Default is white.

(1.0, 1.0, 1.0)
style str

Lighting preset ('default', 'matte', 'glossy', 'sculpted', 'flat').

'default'
zoom float

Camera zoom level. Default is 1.2.

1.2
display_type (matplotlib, interactive, pyvista, object)

'matplotlib': returns a matplotlib figure and axis (default). 'interactive': opens an interactive trame viewer in the browser. 'pyvista': returns a static jupyter widget (legacy behavior). 'object': returns the raw pyvista plotter object.

'matplotlib'
export_path str

If provided, saves the figure to this path.

None
lut (list, ndarray or auto)

Lookup table for categorical data (e.g., labels or clusters), where lut[i] is the color of label i. Label 0 is treated as background and drawn with nan_color, so lut[0] is not used. If 'auto', a distinct color is generated for each label. When provided, cmap and vminmax are ignored and no colorbar is drawn. Default is None (data is treated as continuous).

None
proc_vertices str or None

Whether to process the vertices edges between labels. Only used when lut is provided (continuous data is always plotted as is). Set to None to not perform. 'sharp': Applies sharpening of the resolution of different color vertices (default).

'sharp'

Returns:

Type Description
Axes or Plotter or DisplayObject

returns based on display_type: - 'matplotlib': returns a matplotlib axes object. - 'interactive': returns a trame browser viewer. - 'pyvista': returns a static jupyter widget. - 'object': returns the raw pyvista plotter.

See Also

yabplot.mesh.load_vertexwise_mesh

Examples:

>>> from yabplot.mesh import load_vertexwise_mesh
>>> lh, rh = load_vertexwise_mesh(
...     fsaverage.pial_left, fsaverage.pial_right,
...     d_values_lh, d_values_rh
... )
>>> # If your data was injected under the default 'Data' key
>>> plot_vertexwise(lh, rh, views=['left_lateral', 'right_lateral'])
>>>
>>> # If your data was injected under a custom key
>>> lh['thickness'] = lh_thick_array
>>> rh['thickness'] = rh_thick_array
>>> plot_vertexwise(lh, rh, scalars='thickness', cmap='inferno')
>>>
>>> # If your data are labels (e.g., clusters 1 and 2), color label i with lut[i]
>>> plot_vertexwise(lh, rh, scalars='clusters', lut=['white', 'red', 'blue'])
Source code in yabplot/plotting.py
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
def plot_vertexwise(lh, rh, scalars='Data', ax=None, cbar_kwargs=None, views=None, layout=None, figsize=None,
                    cmap='coolwarm', vminmax=[None, None], nan_color=(1.0, 1.0, 1.0), style='default', zoom=1.2,
                    display_type='matplotlib', export_path=None, lut=None, proc_vertices='sharp'):
    """
    Visualize arbitrary per-vertex scalar data on a user-supplied brain mesh.

    Unlike `plot_cortical`, this function requires no atlas. The user provides
    PyVista PolyData meshes with per-vertex scalar data stored under the key specified
    by `scalars`.

    Parameters
    ----------
    lh : pyvista.PolyData
        Left hemisphere mesh containing a (N,) float array under ``lh[scalars]``.
    rh : pyvista.PolyData
        Right hemisphere mesh containing a (N,) float array under ``rh[scalars]``.
    scalars : str, optional
        The string key corresponding to the scalar data array in the PyVista
        point data dictionary. Default is 'Data'.
    views : list of str, optional
        Can be a list of presets ('left_lateral', 'right_medial', etc.)
        or a dictionary of camera configurations. Defaults to all views.
    layout : tuple (rows, cols), optional
        Grid layout for subplots. If None, auto-calculated.
    figsize : tuple (width, height), optional
        Window size in inches. If None, automatically calculated based on the number of views and layout.
    cmap : str or matplotlib.colors.Colormap, optional
        Colormap. Default is 'coolwarm'.
    vminmax : list [min, max], optional
        Colormap bounds. If [None, None], inferred from data range.
    nan_color : tuple or str, optional
        Color for NaN vertices. Default is white.
    style : str, optional
        Lighting preset ('default', 'matte', 'glossy', 'sculpted', 'flat').
    zoom : float, optional
        Camera zoom level. Default is 1.2.
    display_type : {'matplotlib', 'interactive', 'pyvista', 'object'}, optional
        'matplotlib': returns a matplotlib figure and axis (default).
        'interactive': opens an interactive trame viewer in the browser.
        'pyvista': returns a static jupyter widget (legacy behavior).
        'object': returns the raw pyvista plotter object.
    export_path : str, optional
        If provided, saves the figure to this path.
    lut : list, numpy.ndarray or 'auto', optional
        Lookup table for categorical data (e.g., labels or clusters), where ``lut[i]``
        is the color of label ``i``. Label 0 is treated as background and drawn with
        `nan_color`, so ``lut[0]`` is not used. If 'auto', a distinct color is generated
        for each label. When provided, `cmap` and `vminmax` are ignored and no colorbar
        is drawn. Default is None (data is treated as continuous).
    proc_vertices : str or None, optional
        Whether to process the vertices edges between labels. Only used when `lut` is
        provided (continuous data is always plotted as is).
        Set to None to not perform.
        'sharp': Applies sharpening of the resolution of different color vertices (default).

    Returns
    -------
    matplotlib.axes.Axes or pyvista.Plotter or IPython.display.DisplayObject
        returns based on display_type:
        - 'matplotlib': returns a matplotlib axes object.
        - 'interactive': returns a trame browser viewer.
        - 'pyvista': returns a static jupyter widget.
        - 'object': returns the raw pyvista plotter.

    See Also
    --------
    yabplot.mesh.load_vertexwise_mesh

    Examples
    --------
    >>> from yabplot.mesh import load_vertexwise_mesh
    >>> lh, rh = load_vertexwise_mesh(
    ...     fsaverage.pial_left, fsaverage.pial_right,
    ...     d_values_lh, d_values_rh
    ... )
    >>> # If your data was injected under the default 'Data' key
    >>> plot_vertexwise(lh, rh, views=['left_lateral', 'right_lateral'])
    >>>
    >>> # If your data was injected under a custom key
    >>> lh['thickness'] = lh_thick_array
    >>> rh['thickness'] = rh_thick_array
    >>> plot_vertexwise(lh, rh, scalars='thickness', cmap='inferno')
    >>>
    >>> # If your data are labels (e.g., clusters 1 and 2), color label i with lut[i]
    >>> plot_vertexwise(lh, rh, scalars='clusters', lut=['white', 'red', 'blue'])
    """

    # extract v, f, raw from PyVista meshes
    lh_v, lh_f = extract_polydata(lh)
    lh_vals_raw = lh[scalars]
    rh_v, rh_f = extract_polydata(rh)
    rh_vals_raw = rh[scalars]

    # categorical mode is opt-in: label i is colored with lut[i]
    is_cat = lut is not None
    max_id = None
    if is_cat:
        # labels must be whole numbers (NaN is allowed and treated as background)
        labels = np.concatenate([lh_vals_raw, rh_vals_raw])
        labels = labels[~np.isnan(labels)]
        if not np.all(labels == np.round(labels)):
            raise ValueError("lut requires whole-number labels (e.g., 0, 1, 2) but data contains other values.")
        max_label = int(labels.max()) if labels.size else 0
        if isinstance(lut, str) and lut == 'auto':
            lut = generate_distinct_colors(max_label + 1, seed=42)
        if max_label >= len(lut):
            raise ValueError(f"lut has {len(lut)} colors but data contains label {max_label}.")
        # color range must span the whole lut (not the data) to keep label i on lut[i]
        max_id = len(lut) - 1
        # 'blur' mixes neighbouring label ids, which would draw wrong labels on the edges
        if proc_vertices not in ('sharp', None):
            raise ValueError("proc_vertices must be 'sharp' or None.")
    else:
        # edge processing works per label, so continuous data is plotted as is
        proc_vertices = None

    # render
    return _render_cortical_views(
        lh_v, lh_f, lh_vals_raw, rh_v, rh_f, rh_vals_raw, is_cat, ax, cbar_kwargs,
        views, layout, figsize, cmap, vminmax, nan_color, style,
        zoom, proc_vertices, display_type, export_path, lut_colors=lut, max_id=max_id
    )

yabplot.plotting.plot_connectome(matrix=None, atlas=None, custom_atlas_path=None, ax=None, cbar_kwargs=None, views=None, layout=None, figsize=None, node_color='strength', node_size='strength', node_cmap='binary', node_vminmax=[None, None], edge_threshold='95%', edge_thickness='weight', edge_scaling=1.0, edge_cmap='coolwarm', edge_color=None, edge_alpha=1.0, edge_vminmax=[None, None], edge_curve=0.1, directed=False, style='default', bmesh_type='midthickness', bmesh_alpha=0.15, bmesh_color='lightgray', zoom=1.2, display_type='matplotlib', export_path=None)

visualizes an n x n connectivity matrix as a 3d network in the brain.

calculates spatial centroids for atlas regions and renders connectivity weights as 3d tubes (edges) and spheres (nodes) within a transparent brain hull.

Parameters:

Name Type Description Default
matrix ndarray or dataframe

the (n, n) connectivity matrix. if none, only nodes are plotted. nan values are handled gracefully.

None
atlas str

name of the atlas mapping the regions (e.g., 'aparc', 'aseg').

None
custom_atlas_path str

path to custom atlas files if bypassing the built-in registry.

None
views list of str

list of views to render (e.g., ['left_lateral', 'superior']).

None
layout tuple

plotter grid layout (nrows, ncols). auto-generated if none.

None
figsize tuple

window size in inches (width, height). If None, automatically calculated based on layout.

None
node_color (str, array, dict)

can be 'atlas' (default categorical colors), 'strength' (graph metric), a static color string ('red'), or a custom data array/dict of matching length. default is 'strength' (when no matrix is provided, then 'atlas' is used).

'strength'
node_size (float, str, array, dict)

constant float radius, 'strength' (graph metric), or a custom data array/dict to scale node sizes. default is 'strength' (when no matrix is provided, then 'atlas' is used).

'strength'
node_cmap str

colormap name for mapped node colors. default is 'binary'.

'binary'
node_vminmax list

[vmin, vmax] for node colormap clipping.

[None, None]
edge_threshold float or str

minimum absolute weight to display an edge. strings like '90%' calculate percentiles of the matrix. default is '95%'.

'95%'
edge_thickness float or str

'weight' to scale by connection strength, or a constant float.

'weight'
edge_scaling float

global multiplier for edge tube thickness. default is 1.0.

1.0
edge_cmap str

colormap name for edges. default is 'coolwarm'.

'coolwarm'
edge_color str

constant color for all edges, overriding the colormap.

None
edge_alpha float

opacity of the edges (0.0 to 1.0). default is 1.0.

1.0
edge_vminmax list

[vmin, vmax] for edge colormap clipping.

[None, None]
edge_curve float

amount of bend applied to edges. 0.0 draws straight lines. default is 0.1.

0.1
directed bool

if true, renders asymmetrical connections (full matrix instead of upper triangle).

False
style str

lighting/shading preset ('default', 'matte', 'glossy', etc.).

'default'
bmesh_type str

surface to render as context (e.g., 'midthickness'). default is 'midthickness'.

'midthickness'
bmesh_alpha float

Opacity of the context brain mesh. Default is 0.15.

0.15
bmesh_color str

color of the context brain hull. default is 'lightgray'.

'lightgray'
zoom float

camera zoom level. default is 1.2.

1.2
display_type (matplotlib, interactive, pyvista, object)

'matplotlib': returns a matplotlib figure and axis (default). 'interactive': opens an interactive trame viewer in the browser. 'pyvista': returns a static jupyter widget (legacy behavior). 'object': returns the raw pyvista plotter object.

'matplotlib'
export_path str

path to save the exported image.

None

Returns:

Type Description
Axes or Plotter or DisplayObject

returns based on display_type: - 'matplotlib': returns a matplotlib axes object. - 'interactive': returns a trame browser viewer. - 'pyvista': returns a static jupyter widget. - 'object': returns the raw pyvista plotter.

Source code in yabplot/plotting.py
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
def plot_connectome(matrix=None, atlas=None, custom_atlas_path=None, ax=None, cbar_kwargs=None, views=None, layout=None,
                    figsize=None, node_color='strength', node_size='strength', node_cmap='binary',
                    node_vminmax=[None, None], edge_threshold='95%', edge_thickness='weight',
                    edge_scaling=1.0, edge_cmap='coolwarm', edge_color=None, edge_alpha=1.0,
                    edge_vminmax=[None, None], edge_curve=0.1, directed=False,
                    style='default', bmesh_type='midthickness', bmesh_alpha=0.15,
                    bmesh_color='lightgray', zoom=1.2, display_type='matplotlib', export_path=None):
    """
    visualizes an n x n connectivity matrix as a 3d network in the brain.

    calculates spatial centroids for atlas regions and renders connectivity weights
    as 3d tubes (edges) and spheres (nodes) within a transparent brain hull.

    parameters
    ----------
    matrix : numpy.ndarray or pandas.dataframe, optional
        the (n, n) connectivity matrix. if none, only nodes are plotted.
        nan values are handled gracefully.
    atlas : str, optional
        name of the atlas mapping the regions (e.g., 'aparc', 'aseg').
    custom_atlas_path : str, optional
        path to custom atlas files if bypassing the built-in registry.
    views : list of str, optional
        list of views to render (e.g., ['left_lateral', 'superior']).
    layout : tuple, optional
        plotter grid layout (nrows, ncols). auto-generated if none.
    figsize : tuple, optional
        window size in inches (width, height). If None, automatically calculated based on layout.
    node_color : str, array, dict, optional
        can be 'atlas' (default categorical colors), 'strength' (graph metric), a static
        color string ('red'), or a custom data array/dict of matching length.
        default is 'strength' (when no matrix is provided, then 'atlas' is used).
    node_size : float, str, array, dict, optional
        constant float radius, 'strength' (graph metric),
        or a custom data array/dict to scale node sizes.
        default is 'strength' (when no matrix is provided, then 'atlas' is used).
    node_cmap : str, optional
        colormap name for mapped node colors. default is 'binary'.
    node_vminmax : list, optional
        [vmin, vmax] for node colormap clipping.
    edge_threshold : float or str, optional
        minimum absolute weight to display an edge. strings like '90%'
        calculate percentiles of the matrix. default is '95%'.
    edge_thickness : float or str, optional
        'weight' to scale by connection strength, or a constant float.
    edge_scaling : float, optional
        global multiplier for edge tube thickness. default is 1.0.
    edge_cmap : str, optional
        colormap name for edges. default is 'coolwarm'.
    edge_color : str, optional
        constant color for all edges, overriding the colormap.
    edge_alpha : float, optional
        opacity of the edges (0.0 to 1.0). default is 1.0.
    edge_vminmax : list, optional
        [vmin, vmax] for edge colormap clipping.
    edge_curve : float, optional
        amount of bend applied to edges. 0.0 draws straight lines. default is 0.1.
    directed : bool, optional
        if true, renders asymmetrical connections (full matrix instead of upper triangle).
    style : str, optional
        lighting/shading preset ('default', 'matte', 'glossy', etc.).
    bmesh_type : str, optional
        surface to render as context (e.g., 'midthickness'). default is 'midthickness'.
    bmesh_alpha : float, optional
        Opacity of the context brain mesh. Default is 0.15.
    bmesh_color : str, optional
        color of the context brain hull. default is 'lightgray'.
    zoom : float, optional
        camera zoom level. default is 1.2.
    display_type : {'matplotlib', 'interactive', 'pyvista', 'object'}, optional
        'matplotlib': returns a matplotlib figure and axis (default).
        'interactive': opens an interactive trame viewer in the browser.
        'pyvista': returns a static jupyter widget (legacy behavior).
        'object': returns the raw pyvista plotter object.
    export_path : str, optional
        path to save the exported image.

    returns
    -------
    matplotlib.axes.Axes or pyvista.Plotter or IPython.display.DisplayObject
        returns based on display_type:
        - 'matplotlib': returns a matplotlib axes object.
        - 'interactive': returns a trame browser viewer.
        - 'pyvista': returns a static jupyter widget.
        - 'object': returns the raw pyvista plotter.
    """

    # detect atlas category and validate inputs
    bmesh_type = bmesh_type or 'midthickness'
    category = None
    if custom_atlas_path:
        files = os.listdir(custom_atlas_path)
        if any(f.endswith('.csv') for f in files): category = 'cortical'
        elif any(f.endswith('.vtk') or f.endswith('.gii') for f in files): category = 'subcortical'
        else: raise ValueError("could not detect atlas type in custom path.")
    else:
        atlas = atlas or 'aparc'
        resources = get_available_resources()
        if atlas in resources.get('cortical', []): category = 'cortical'
        elif atlas in resources.get('subcortical', []): category = 'subcortical'
        else: raise ValueError(f"atlas '{atlas}' not found in registry.")

    # load visual context brain securely
    bmesh = {}
    if bmesh_type:
        b_lh_path, b_rh_path = get_surface_paths(bmesh_type, 'bmesh')
        bmesh['L'] = load_gii2pv(b_lh_path)
        bmesh['R'] = load_gii2pv(b_rh_path)

    # compute spatial centers
    centroids, region_names, atlas_colors = _extract_centroids(category, atlas, custom_atlas_path, bmesh_type)

    # matrix parsing and nan-proof thresholding
    n_nodes = len(region_names)
    if matrix is not None:
        if isinstance(matrix, pd.DataFrame):
            mat = matrix.reindex(index=region_names, columns=region_names).values if set(region_names).intersection(matrix.index) else matrix.values
        else:
            mat = np.array(matrix, dtype=float)

        if mat.shape != (n_nodes, n_nodes):
            raise ValueError(f"matrix shape {mat.shape} does not match atlas regions ({n_nodes}).")

        if isinstance(edge_threshold, str) and edge_threshold.endswith('%'):
            perc = float(edge_threshold.strip('%'))
            upper_tri = np.abs(mat[np.triu_indices_from(mat, k=1)])
            valid_edges = upper_tri[~np.isnan(upper_tri)]
            actual_thresh = np.percentile(valid_edges, perc) if len(valid_edges) > 0 else 0
        else:
            actual_thresh = float(edge_threshold)
    else:
        mat, actual_thresh = np.zeros((n_nodes, n_nodes)), 1.0

    # build node geometry
    node_cloud = pv.PolyData(np.array([centroids[n] for n in region_names]))

    # parse node sizes (constant, 'strength', or custom data array)
    raw_sizes, is_size_mapped, size_name = _parse_node_metrics(node_size, mat, actual_thresh, directed, n_nodes, region_names)
    if is_size_mapped:
        s_min, s_max = np.nanmin(raw_sizes), np.nanmax(raw_sizes)
        # scale radii between 0 and 4 based on the data
        node_cloud.point_data['Radius'] = 0.0 + 4.0 * (raw_sizes - s_min) / (s_max - s_min) if s_max > s_min else np.full(n_nodes, 2.0)
    else:
        node_cloud.point_data['Radius'] = raw_sizes

    # parse node colors
    is_node_mapped, color_name = False, None
    n_vmin, n_vmax = None, None

    if matrix is None:
        node_color = 'atlas'
        node_size = 2.0

    if isinstance(node_color, str) and node_color == 'atlas':
        # use default atlas categorical colors
        node_cloud.point_data['Color'] = np.array(
            [np.array(to_rgba(atlas_colors.get(n, '#cccccc'))[:3]) * 255 for n in region_names]
        ).astype(np.uint8)
        rgb_mode = True

    elif isinstance(node_color, str) and node_color != 'strength':
        # use a constant user-provided color string (e.g., 'red')
        node_cloud.point_data['Color'] = np.array(
            [np.array(to_rgba(node_color)[:3]) * 255 for _ in region_names]
        ).astype(np.uint8)
        rgb_mode = True

    elif isinstance(node_color, dict) and node_color and isinstance(next(iter(node_color.values())), str):
        # use a custom dictionary mapping regions to specific color strings
        node_cloud.point_data['Color'] = np.array(
            [np.array(to_rgba(node_color.get(n, 'white'))[:3]) * 255 for n in region_names]
        ).astype(np.uint8)
        rgb_mode, is_node_mapped = True, False

    else:
        # map scalar values (like 'strength' or custom data) to a colormap
        raw_colors, is_color_mapped, color_name = _parse_node_metrics(node_color, mat, actual_thresh, directed, n_nodes, region_names)
        node_cloud.point_data['Color'] = raw_colors
        rgb_mode, is_node_mapped = False, True

        n_vmin = node_vminmax[0] if node_vminmax[0] is not None else np.nanmin(raw_colors)
        n_vmax = node_vminmax[1] if node_vminmax[1] is not None else np.nanmax(raw_colors)
        if n_vmin == n_vmax: n_vmin, n_vmax = n_vmin - 0.1, n_vmax + 0.1

    nodes_mesh = node_cloud.glyph(
        scale='Radius', geom=pv.Sphere(radius=1.0, theta_resolution=16, phi_resolution=16), orient=False
    )

    # build edge geometry
    merged_edges, e_vmin, e_vmax = None, None, None
    if matrix is not None:
        merged_edges, e_vmin, e_vmax = _build_edges(
            mat, actual_thresh, directed, centroids, region_names,
            edge_curve, edge_thickness, edge_scaling
        )
        if e_vmin is not None:
            e_vmin = edge_vminmax[0] if edge_vminmax[0] is not None else e_vmin
            e_vmax = edge_vminmax[1] if edge_vminmax[1] is not None else e_vmax
            if e_vmin == e_vmax: e_vmin, e_vmax = e_vmin - 0.1, e_vmax + 0.1

    # scene layout configuration
    sel_views = get_view_configs(views)
    ax, display_type, figsize = prepare_plotter(ax, display_type, sel_views, layout, figsize)

    is_edge_mapped = (merged_edges is not None) and (edge_color is None)
    edge_metric_name = "data" if edge_thickness == 'weight' else None
    needs_bottom = is_node_mapped or is_edge_mapped or size_name or edge_metric_name

    plotter, ncols, nrows = setup_plotter(sel_views, layout, figsize, display_type, needs_bottom_row=needs_bottom)
    shading_params = get_shading_preset(style)
    node_mapper, edge_mapper = None, None

    # render loop over views
    for i, (view_name, cfg) in enumerate(sel_views.items()):
        plotter.subplot(i // ncols, i % ncols)
        add_context_to_view(plotter, bmesh, cfg['side'], bmesh_alpha, bmesh_color, **shading_params)

        # render nodes
        node_props = shading_params.copy()
        node_props.update({'scalars': 'Color', 'rgb': rgb_mode, 'show_scalar_bar': False})
        if not rgb_mode: node_props.update({'cmap': node_cmap, 'clim': [n_vmin, n_vmax]})

        n_actor = plotter.add_mesh(nodes_mesh, **node_props)
        if not rgb_mode and node_mapper is None: node_mapper = n_actor.mapper

        # render edges
        if merged_edges is not None:
            edge_props = shading_params.copy()
            edge_props.update({'opacity': edge_alpha, 'show_scalar_bar': False})
            if edge_color is not None:
                edge_props.update({'color': edge_color})
            else:
                edge_props.update({'scalars': 'Connectivity', 'cmap': edge_cmap, 'clim': [e_vmin, e_vmax]})

            e_actor = plotter.add_mesh(merged_edges, **edge_props)
            if edge_color is None and edge_mapper is None: edge_mapper = e_actor.mapper

        set_camera(plotter, cfg, zoom=zoom)
        plotter.hide_axes()

    # colorbars
    cbar_info = []
    if needs_bottom:
        # use concise titles for colorbars to prevent layout squeezing
        edge_title = "edge weights" if is_edge_mapped else "edges"
        node_title = f"node {color_name}" if is_node_mapped and color_name else "nodes"

        if display_type != 'matplotlib':
            add_colorbars(plotter=plotter, mappers=[edge_mapper, node_mapper],
                          titles=[edge_title, node_title], nrows=nrows, figsize=figsize)
        else:
            if edge_mapper is not None:
                cbar_info.append({'cmap': edge_cmap, 'vminmax': [e_vmin, e_vmax], 'title': edge_title})
            if node_mapper is not None:
                cbar_info.append({'cmap': node_cmap, 'vminmax': [n_vmin, n_vmax], 'title': node_title})

    return finalize_plot(plotter, export_path=export_path, display_type=display_type, ax=ax, cbar_info=cbar_info, cbar_kwargs=cbar_kwargs)

yabplot.plotting.clear_cache()

manually clears the global geometry cache to free ram.

Source code in yabplot/plotting.py
824
825
826
827
828
829
def clear_cache():
    """manually clears the global geometry cache to free ram."""
    global _STATIC_CACHE
    _STATIC_CACHE.clear()
    gc.collect()
    print("geometry cache cleared.")