Skip to content

ddd

Additional plotting parameters for K3d backend.

Source code in navis/plotting/settings.py
223
224
225
226
227
228
229
230
231
232
@dataclass
class K3dSettings(BasePlottingSettings):
    """Additional plotting parameters for K3d backend."""

    _name = "k3d backend"

    height: int = 600
    inline: bool = True
    legend_group: Optional[str] = None
    plot: Optional["k3d.Plot"] = None

Additional plotting parameters for Octarine backend.

Source code in navis/plotting/settings.py
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
@dataclass
class OctarineSettings(BasePlottingSettings):
    """Additional plotting parameters for Octarine backend."""

    _name = "octarine backend"

    clear: bool = False
    center: bool = True
    viewer: Optional[Union["octarine.Viewer", Literal["new"]]] = None
    random_ids: bool = False
    camera: Literal["ortho", "perspective"] = "ortho"
    control: Literal["trackball", "panzoom", "fly", "orbit"] = "trackball"
    show: bool = True
    size: Optional[Tuple[int, int]] = None
    offscreen: bool = False
    spacing: Optional[Tuple[float, float, float]] = None

    # These are viewer-specific settings that we must not pass to the plotting
    # function
    _viewer_settings: tuple[str] = (
        "clear",
        "center",
        "viewer",
        "camera",
        "control",
        "show",
        "size",
        "offscreen",
        "scatter_kws",
        "spacing"
    )

Additional plotting parameters for Plotly backend.

Source code in navis/plotting/settings.py
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
@dataclass
class PlotlySettings(BasePlottingSettings):
    """Additional plotting parameters for Plotly backend."""

    _name = "plotly backend"

    fig: Optional[Union["plotly.Figure", dict]] = None
    inline: bool = True
    title: Optional[str] = None
    fig_autosize: bool = True
    hover_name: Optional[str] = False
    hover_id: bool = False
    legend: bool = True
    legend_orientation: Literal["h", "v"] = "v"
    legend_group: Optional[str] = None
    volume_legend: bool = False
    width: Optional[int] = None
    height: Optional[int] = 600
    linewidth: Optional[float] = None  # for plotly, linewidth 1 is too thin, we default to 3 in graph_objs.py
    linestyle: str = "-"

Additional plotting parameters for Vispy backend.

Source code in navis/plotting/settings.py
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
@dataclass
class VispySettings(BasePlottingSettings):
    """Additional plotting parameters for Vispy backend."""

    _name = "vispy backend"

    clear: bool = False
    center: bool = True
    combine: bool = False
    title: Optional[str] = None
    viewer: Optional["navis.Viewer"] = None
    shininess: float = 0
    shading: str = "smooth"
    size: Optional[Tuple[int, int]] = (800, 600)
    show: bool = True
    name: Optional[str] = None

Plot3d() helper function to generate k3d 3D plots. This is just to improve readability and structure of the code.

Source code in navis/plotting/ddd.py
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
def plot3d_k3d(x, **kwargs):
    """
    Plot3d() helper function to generate k3d 3D plots. This is just to
    improve readability and structure of the code.
    """
    # Lazy import because k3d is not (yet) a hard dependency
    try:
        import k3d
    except ModuleNotFoundError:
        raise ModuleNotFoundError(
            "navis.plot3d() with `k3d` backend requires the k3d library "
            "to be installed:\n  pip3 install k3d -U"
        )

    from .k3d.k3d_objects import neuron2k3d, volume2k3d, scatter2k3d

    settings = K3dSettings().update_settings(**kwargs)

    # Parse objects to plot
    (neurons, volumes, points, visual) = utils.parse_objects(x)

    neuron_cmap, volumes_cmap = prepare_colormap(
        settings.color,
        neurons=neurons,
        volumes=volumes,
        palette=settings.palette,
        color_by=None,
        alpha=settings.alpha,
        color_range=255,
    )

    data = []
    if neurons:
        data += neuron2k3d(neurons, neuron_cmap, settings)
    if volumes:
        data += volume2k3d(volumes, volumes_cmap, settings)
    if points:
        data += scatter2k3d(points, **settings.scatter_kws)

    # If not provided generate a plot
    if not settings.plot:
        plot = k3d.plot(height=settings.height)
        plot.camera_rotate_speed = 5
        plot.camera_zoom_speed = 2
        plot.camera_pan_speed = 1
        plot.grid_visible = False

    # Add data
    for trace in data:
        plot += trace

    if settings.inline and utils.is_jupyter():
        plot.display()
    else:
        logger.info("Use the `.display()` method to show the plot.")
        return plot

Plot3d() helper function to generate octarine 3D plots.

This is just to improve readability. Its only purpose is to find the existing viewer or generate a new one.

Source code in navis/plotting/ddd.py
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
501
502
503
504
505
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
def plot3d_octarine(x, **kwargs):
    """Plot3d() helper function to generate octarine 3D plots.

    This is just to improve readability. Its only purpose is to find the
    existing viewer or generate a new one.

    """
    # Lazy import because octarine is not a hard dependency
    try:
        import octarine as oc
    except ModuleNotFoundError:
        raise ModuleNotFoundError(
            "navis.plot3d() with the `octarine` backend requires the `octarine3d` library "
            "to be installed:\n  pip3 install octarine3 octarine-navis-plugin -U"
        )

    if not hasattr(oc.Viewer, "add_neurons"):
        raise ModuleNotFoundError(
            "Looks like the navis plugin for octarine is not installed. "
            "Please install it via pip:\n  pip install octarine-navis-plugin"
        )

    settings = OctarineSettings().update_settings(**kwargs)

    # Parse objects to plot
    (neurons, volumes, points, visuals) = utils.parse_objects(x)

    # Check if any existing viewer has already been closed
    if isinstance(getattr(config, "primary_viewer", None), oc.Viewer):
        try:
            getattr(config, "primary_viewer").canvas.__repr__()
        except RuntimeError:
            config.primary_viewer = None

    if settings.viewer in (None, "new"):
        # If it does not exists yet, initialize a canvas object and make global
        if (
            not isinstance(getattr(config, "primary_viewer", None), oc.Viewer)
            or settings.viewer == "new"
        ):
            viewer = config.primary_viewer = oc.Viewer(
                size=settings.size,
                camera=settings.camera,
                control=settings.control,
                show=False,
                offscreen=settings.offscreen or os.environ.get("NAVIS_HEADLESS", False),
            )
        else:
            viewer = getattr(config, "primary_viewer", None)
    else:
        viewer = settings.pop("viewer", getattr(config, "primary_viewer"))

    # Make sure viewer is visible
    if settings.show:
        viewer.show()

    # We need to pop clear/clear3d to prevent clearing again later
    if settings.clear:
        settings.clear = False  # clear only once
        viewer.clear()

    # Add object (the viewer currently takes care of producing the visuals)
    if neurons:
        # We need to pop viewer-specific settings to prevent errors in plotting functions
        neuron_settings = settings.to_dict()
        for key in settings._viewer_settings:
            neuron_settings.pop(key, None)
        viewer.add_neurons(neurons, center=settings.get("center", True), **neuron_settings)
    if volumes:
        for v in volumes:
            viewer.add_mesh(
                v,
                name=getattr(v, "name", None),
                color=getattr(v, "color", (0.95, 0.95, 0.95, 0.1)),
                alpha=getattr(v, "alpha", None),
                center=settings.center,
            )
    if points:
        for p in points:
            viewer.add_points(p, center=settings.center, **settings.scatter_kws)

    return viewer

Plot3d() helper function to generate plotly 3D plots. This is just to improve readability and structure of the code.

Source code in navis/plotting/ddd.py
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
def plot3d_plotly(x, **kwargs):
    """
    Plot3d() helper function to generate plotly 3D plots. This is just to
    improve readability and structure of the code.
    """
    # Lazy import because plotly is not a hard dependency
    try:
        import plotly.graph_objs as go
        from .plotly.graph_objs import (
            neuron2plotly,
            volume2plotly,
            scatter2plotly,
            layout2plotly,
        )
    except ModuleNotFoundError:
        raise ModuleNotFoundError(
            "navis.plot3d() with the `plotly` backend requires the `plotly` library "
            "to be installed:\n  pip3 install plotly -U"
        )

    settings = PlotlySettings().update_settings(**kwargs)

    # Parse objects to plot
    (neurons, volumes, points, visual) = utils.parse_objects(x)

    neuron_cmap, volumes_cmap = prepare_colormap(
        settings.color,
        neurons=neurons,
        volumes=volumes,
        palette=settings.palette,
        color_by=None,
        alpha=settings.alpha,
        color_range=255,
    )

    data = []
    if neurons:
        data += neuron2plotly(neurons, neuron_cmap, settings)
    if volumes:
        data += volume2plotly(volumes, volumes_cmap, settings)
    if points:
        data += scatter2plotly(points, **settings.scatter_kws)

    layout = layout2plotly(**settings.to_dict())

    # If not provided generate a figure dictionary
    fig = settings.fig if settings.fig else go.Figure(layout=layout)
    if not isinstance(fig, (dict, go.Figure)):
        raise TypeError(
            "`fig` must be plotly.graph_objects.Figure or dict, got " f"{type(fig)}"
        )

    # Add data
    for trace in data:
        fig.add_trace(trace)

    if settings.inline and utils.is_jupyter():
        fig.show()
    else:
        logger.info("Use the `.show()` method to plot the figure.")
        return fig

Plot3d() helper function to generate vispy 3D plots.

This is just to improve readability. Its only purpose is to find the existing viewer or generate a new one.

Source code in navis/plotting/ddd.py
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
def plot3d_vispy(x, **kwargs):
    """Plot3d() helper function to generate vispy 3D plots.

    This is just to improve readability. Its only purpose is to find the
    existing viewer or generate a new one.

    """
    from .vispy.viewer import Viewer

    # If this likely the first invoke, warn the user that vispy is deprecated
    if not hasattr(config, "primary_viewer"):
        warnings.warn(
            (
                "The `vispy` backend is depcrecated and will be removed in a future version of navis. "
                "We recommend to use the `octarine` backend instead. If that is for some reason not possible, "
                "please let us know via the issue tracker at https://github.com/navis-org/navis/issues asap."
            ),
            DeprecationWarning,
            stacklevel=2,
        )

    settings = VispySettings().update_settings(**kwargs)

    # Parse objects to plot
    (neurons, volumes, points, visuals) = utils.parse_objects(x)

    if settings.viewer in (None, "new"):
        # If does not exists yet, initialise a canvas object and make global
        if (
            not isinstance(getattr(config, "primary_viewer", None), Viewer)
            or settings.viewer == "new"
        ):
            viewer = config.primary_viewer = Viewer(size=settings.size)
        else:
            viewer = getattr(config, "primary_viewer", None)
    else:
        viewer = settings.viewer

    # Make sure viewer is visible
    if settings.show:
        viewer.show()

    # We need to pop clear/clear3d to prevent clearing again later
    if settings.clear:
        settings.clear = False
        viewer.clear()

    # Add objects (the viewer currently takes care of producing the visuals)
    if neurons:
        viewer.add(neurons, **settings.to_dict())
    if volumes:
        viewer.add(volumes, **settings.to_dict())
    if points:
        viewer.add(points, scatter_kws=settings.scatter_kws)

    return viewer