Using the vectors
layer#
In this document, you will learn about the napari
vectors
layer, including
how to display many vectors simultaneously and adjust their properties.
For more information about layers, refer to Layers at a glance.
Note
Vector layers can be added only programmatically, i.e., in the console, or using a script, not from the GUI. Please refer to A simple example and use the code there to add a vectors layer first, then explore the GUI controls.
When to use the vectors
layer#
The vectors
layer allows you to display many vectors with defined starting
points and directions. It is particularly useful for people who want to
visualize large vector fields, for example if you are doing polarization
microscopy. You can adjust the color, width, and length of all the vectors from
the console or from the GUI.
A simple example#
You can create a new viewer and add vectors in one go using the
napari.view_vectors()
method, or if you already have an existing viewer,
you can add vectors to it using viewer.add_vectors
. The API of both methods is
the same. In these examples we’ll mainly use add_vectors
to overlay vectors
onto an existing image.
In this example, we will overlay vectors on the image of a photographer:
import napari
import numpy as np
from skimage import data
# create vector data
n = 250
vectors = np.zeros((n, 2, 2), dtype=np.float32)
phi_space = np.linspace(0, 4 * np.pi, n)
radius_space = np.linspace(0, 100, n)
# assign x-y projection
vectors[:, 1, 0] = radius_space * np.cos(phi_space)
vectors[:, 1, 1] = radius_space * np.sin(phi_space)
# assign x-y position
vectors[:, 0] = vectors[:, 1] + 256
# add the image
viewer = napari.view_image(data.camera(), name='photographer')
# add the vectors
vectors_layer = viewer.add_vectors(vectors, edge_width=3)
MESA: error: ZINK: vkCreateInstance failed (VK_ERROR_INCOMPATIBLE_DRIVER)
glx: failed to create drisw screen
Show code cell source
from napari.utils import nbscreenshot
nbscreenshot(viewer, alt_text="Vectors overlaid on an image")
Using the GUI to manipulate vectors#
Before you can use the GUI to manipulate vectors, you must load a vector layer.
Please refer to A simple example to add a vectors
layer
first, then explore the editing options the GUI provides.
Buttons
Pan/zoom - is the default mode of the layer and supports panning and zooming. Press the
1
key when the layer is selected to use this mode.Transform - enables you to rotate, scale, or translate the layer. Note: at present this feature is limited to 2D viewer display mode. To reset the transformation, you can Option/Alt-click the transform button (a confirmation dialog will open to confirm the reset). Press the
2
key when the layer is selected to use this mode.
Controls
Opacity - click and hold the circle on the opacity slider bar and adjust it to any value between 0.00 (clear) and 1.00 (completely opaque).
Width - adjusting the width makes the vectors appear thicker or thinner. Use the + and - buttons on either side of the width bar to adjust width or click on the number in the middle of the bar and enter a value. The minimum value is 0.10.
Length - adjusting the length makes the vector longer or shorter. Use the + and - buttons on either side of the length bar to adjust length or click on the number in the middle of the bar and enter a value. The minimum value is 0.10.
Blending -
blending
has the options ofopaque
,translucent
,translucent no depth
,minimum
, oradditive
in the dropdown. Refer to the Blending layers section of Layers at a glance for an explanation of each type of blending.Edge color mode - select
direct
,cycle
, orcolormap
from the dropdown.Direct (default mode) allows each vector to be set arbitrarily.
Cycle allows the color to be set via a color cycle over an attribute.
Colormap allows the color to be set via a color map over an attribute.
Edge color - click the thumbnail next to
edge color:
to select or create a color from the pallette.Out of slice - if this box is checked,
out of slice
is on or true. If this box is not checked,out of slice
is off or false. If it is on or true, vectors slightly out of slice are rendered.
Vector starting position#
The starting position of vectors cannot be edited from the GUI. Nor is it
possible to draw vectors from the GUI. If you want to draw lines using the GUI
you should use the Lines
shape inside a shapes
layer.
3D rendering#
All layers can be rendered in both 2D and 3D. One of the viewer buttons at the bottom of the left panel can toggle between these 2 modes. When in 2D, the button looks like this: , ready to switch to 3D mode. When in 3D, the button looks like this: , ready to switch to 2D mode.
The number of dimensions sliders will be 2 or 3 less than the total number of dimensions of the layer, allowing you to browse volumetric timeseries data and other high dimensional data. See nD vectors to see shapes in both 2D and 3D:
Arguments of view_vectors
and add_vectors
#
view_vectors()
and add_vectors()
accept the same layer-creation parameters.
help(napari.view_vectors)
Show code cell output
Help on function view_vectors in module napari.view_layers:
view_vectors(data=None, *, affine=None, blending='translucent', cache=True, edge_color='red', edge_color_cycle=None, edge_colormap='viridis', edge_contrast_limits=None, edge_width=1, experimental_clipping_planes=None, feature_defaults=None, features=None, length=1, metadata=None, name=None, ndim=None, opacity=0.7, out_of_slice_display=False, projection_mode='none', properties=None, property_choices=None, rotate=None, scale=None, shear=None, translate=None, units=None, vector_style='triangle', visible=True, title='napari', ndisplay=2, order=(), show=True, camera: napari.components.camera.Camera = None, cursor: napari.components.cursor.Cursor = None, dims: napari.components.dims.Dims = None, grid: napari.components.grid.GridCanvas = None, layers: napari.components.layerlist.LayerList = None, help: str = '', status: Union[str, dict] = 'Ready', tooltip: napari.components.tooltip.Tooltip = None, theme: str = None, mouse_over_canvas: bool = False) -> napari.viewer.Viewer
Create a viewer and add a vectors layer.
Parameters
----------
data : (N, 2, D) or (N1, N2, ..., ND, D) array
An (N, 2, D) array is interpreted as "coordinate-like" data and a
list of N vectors with start point and projections of the vector in
D dimensions. An (N1, N2, ..., ND, D) array is interpreted as
"image-like" data where there is a length D vector of the
projections at each pixel.
affine : n-D array or napari.utils.transforms.Affine
(N+1, N+1) affine transformation matrix in homogeneous coordinates.
The first (N, N) entries correspond to a linear transform and
the final column is a length N translation vector and a 1 or a napari
`Affine` transform object. Applied as an extra transform on top of the
provided scale, rotate, and shear values.
axis_labels : tuple of str, optional
Dimension names of the layer data.
If not provided, axis_labels will be set to (..., 'axis -2', 'axis -1').
blending : str
One of a list of preset blending modes that determines how RGB and
alpha values of the layer visual get mixed. Allowed values are
{'opaque', 'translucent', and 'additive'}.
cache : bool
Whether slices of out-of-core datasets should be cached upon retrieval.
Currently, this only applies to dask arrays.
edge_color : str
Color of all of the vectors.
edge_color_cycle : np.ndarray, list
Cycle of colors (provided as string name, RGB, or RGBA) to map to edge_color if a
categorical attribute is used color the vectors.
edge_colormap : str, napari.utils.Colormap
Colormap to set vector color if a continuous attribute is used to set edge_color.
edge_contrast_limits : None, (float, float)
clims for mapping the property to a color map. These are the min and max value
of the specified property that are mapped to 0 and 1, respectively.
The default value is None. If set the none, the clims will be set to
(property.min(), property.max())
edge_width : float
Width for all vectors in pixels.
experimental_clipping_planes : list of dicts, list of ClippingPlane, or ClippingPlaneList
Each dict defines a clipping plane in 3D in data coordinates.
Valid dictionary keys are {'position', 'normal', and 'enabled'}.
Values on the negative side of the normal are discarded if the plane is enabled.
feature_defaults : dict[str, Any] or DataFrame
The default value of each feature in a table with one row.
features : dict[str, array-like] or DataFrame
Features table where each row corresponds to a vector and each column
is a feature.
length : float
Multiplicative factor on projections for length of all vectors.
metadata : dict
Layer metadata.
name : str
Name of the layer.
ndim : int
Number of dimensions for vectors. When data is not None, ndim must be D.
An empty vectors layer can be instantiated with arbitrary ndim.
opacity : float
Opacity of the layer visual, between 0.0 and 1.0.
out_of_slice_display : bool
If True, renders vectors not just in central plane but also slightly out of slice
according to specified point marker size.
projection_mode : str
How data outside the viewed dimensions but inside the thick Dims slice will
be projected onto the viewed dimenions.
properties : dict {str: array (N,)}, DataFrame
Properties for each vector. Each property should be an array of length N,
where N is the number of vectors.
property_choices : dict {str: array (N,)}
possible values for each property.
rotate : float, 3-tuple of float, or n-D array.
If a float convert into a 2D rotation matrix using that value as an
angle. If 3-tuple convert into a 3D rotation matrix, using a yaw,
pitch, roll convention. Otherwise assume an nD rotation. Angles are
assumed to be in degrees. They can be converted from radians with
np.degrees if needed.
scale : tuple of float
Scale factors for the layer.
shear : 1-D array or n-D array
Either a vector of upper triangular values, or an nD shear matrix with
ones along the main diagonal.
translate : tuple of float
Translation values for the layer.
units : tuple of str or pint.Unit, optional
Units of the layer data in world coordinates.
If not provided, the default units are assumed to be pixels.
vector_style : str
One of a list of preset display modes that determines how vectors are displayed.
Allowed values are {'line', 'triangle', and 'arrow'}.
visible : bool
Whether the layer visual is currently being displayed.
title : string, optional
The title of the viewer window. By default 'napari'.
ndisplay : {2, 3}, optional
Number of displayed dimensions. By default 2.
order : tuple of int, optional
Order in which dimensions are displayed where the last two or last
three dimensions correspond to row x column or plane x row x column if
ndisplay is 2 or 3. By default None
axis_labels : list of str, optional
Dimension names. By default they are labeled with sequential numbers
show : bool, optional
Whether to show the viewer after instantiation. By default True.
Returns
-------
viewer : :class:`napari.Viewer`
The newly-created viewer.
Changing vector length, width, and color#
Scale the length of all the vectors on a layer using the layer.length
property.
Set the width of all the vectors in a layer using the layer.width
property.
Set the color of all the vectors in a layer using the layer.edge_color
property.
Vectors data#
The input data to the vectors
layer must be an Nx2xD
NumPy array
representing N
vectors with start position and projection values in D
dimensions, or it must be an N1xN2 ... xNDxD
array where each of the first
D
dimensions corresponds to the voxel of the location of the vector, and the
last dimension contains the D
values of the projection of that vector. The
former representation is useful when you have vectors that can start in
arbitrary positions in the canvas. The latter representation is useful when your
vectors are defined on a grid, say corresponding to the voxels of an image, and
you have one vector per grid.
Here is an example from Add vectors image of a grid of vectors defined over a random image:
Regardless of how the data is passed, we convert it to the Nx2xD
representation internally. This representation is accessible through the
layer.data
property.