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)

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

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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
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):
    """
    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').

    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):]

    # 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
    )

yabplot.plotting.plot_subcortical(data=None, atlas=None, custom_atlas_path=None, ax=None, cbar_kwargs=None, views=None, layout=None, figsize=None, cmap='coolwarm', 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))

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. Ignored if data is None. Default is 'coolwarm'.

'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 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').

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)

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
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
374
375
376
377
378
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
def plot_subcortical(data=None, atlas=None, custom_atlas_path=None, ax=None, cbar_kwargs=None, views=None, layout=None,
                     figsize=None, cmap='coolwarm', 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)):
    """
    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. Ignored if `data` is None. Default is 'coolwarm'.
    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').
    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}.

    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 = '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:
        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:
        colors = generate_distinct_colors(len(rmesh_names), seed=42)
        d_atlas_colors = {name: color for name, color in zip(rmesh_names, colors)}
        c_vlim = [0, 1]

    # 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)
    plotter, ncols, nrows = setup_plotter(sel_views, layout, figsize, display_type,
                                           needs_bottom_row=needs_bottom)


    # get shading parameters from style
    shading_params = get_shading_preset(style)
    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
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
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 (e.g. 'midthickness', 'pial').

'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.

Source code in yabplot/plotting.py
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
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
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 (e.g. 'midthickness', 'pial').
    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.
    """

    # 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)

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

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')
Source code in yabplot/plotting.py
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
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
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):
    """
    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.

    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')
    """

    # 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]

    # render
    return _render_cortical_views(
        lh_v, lh_f, lh_vals_raw, rh_v, rh_f, rh_vals_raw, False, ax, cbar_kwargs,
        views, layout, figsize, cmap, vminmax, nan_color, style,
        zoom, None, display_type, export_path
    )

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
 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
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
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)