Using the points layer#

In this document, you will learn about the napari Points layer, including displaying points over an image that have been found in an automated fashion, or manually annotating an image with points. You will also understand how to add a points layer and edit it from the GUI and from the console.

For more information about layers, refer to Layers at a glance.

When to use the points layer#

The points layer allows you to display an NxD array of N points in D coordinates. You can adjust the size, face color, and edge color of all the points independently. You can also adjust opacity and symbol representing all the points simultaneously.

Each data point can have annotations associated with it using the Points.properties dictionary. These properties can be used to set the face and edge colors of the points. For example, when displaying points of different classes/types, one could automatically set color the individual points by their respective class/type. For more details on point properties, see Setting point edge and face color with properties or point annotation tutorial.

Creating and editing the points layer using the GUI#

The GUI contains following tools in the layer controls panel for the points layer:

  • Buttons

    • Delete selected points

    • Add points

    • Select points

    • Pan/zoom

  • Controls

    • Opacity

    • Point size

    • Blending

    • Symbol

    • Face color

    • Edge color

    • Display text

    • Out of slice

  • Other tools

    • New points layer button

    • 2D/3D button

Buttons#

  • Deleting points image: Delete points tool

    Points can be deleted after they have been selected. First select the point or points to delete, then click on the delete button in the layer controls panel or press the delete key on your keyboard.

  • Adding points image: Add points tool

    New points can be added using the point adding tool, shown above, from the layer controls panel. Points can then be added by clicking in the canvas.

    Note: Clicking and dragging moves the image, just as pan/zoom does. Just click where you want the point to go. You cannot adjust the point by clicking and dragging. Use the point size control to make it larger or smaller.

    If you have a multidimensional points layer then the coordinates of the new point will keep track of the currently viewed slice the point has been added to.

    Quickly select the add points tool by pressing the 2 key when the points layer is selected. The add points tool supports panning and zooming.

    Additionally, you can select all the points in the currently viewed slice by pressing the a key and all the points in the layer (across all slices) using Shift-a.

    Note: Pressing either keybinding again will toggle the selection, so you can select all points in a layer and the deselect points from a slice.

  • Selecting points image: Select points tool

    Select a point using the tool (shown above) and then clicking on that point. You can select multiple points by continuing to shift+click on additional points, or by dragging a bounding box around the points you want to select. You can quickly switch to the select points tool by pressing the 3 key when the points layer is selected. Select all the points in the currently viewed slice by clicking the a key while in select mode.

    Using the select points tool disables pan and zoom functionality. This allows you to select points on the layer. Temporarily re-enable pan and zoom by pressing and holding the spacebar. This feature can be useful if you want to move around the points layer as you create your selection.

  • Pan/zoom image: Pan/zoom tool

    The default mode of the points layer supports panning and zooming, as in the image layer. This mode is represented by the magnifying glass in the layers control panel, and while it is selected, the Add point, Delete selected points, and Select points tools are all disabled. Those options are supported only when viewing a layer using 2D rendering. Return to pan and zoom mode by pressing the 4 key when the points layer is selected.

Controls#

  • Opacity

    The opacity slider adjusts the opacity of a point or points from 0 (transparent) to 1.00 (completely opaque).

  • Point size

    Point size can be adjusted from 1 to 100 using the point size slider.

  • Blending

    Select translucent, translucent no depth, additive, minimum, or opaque from the dropdown. Refer to the Blending layers section of Layers at a glance for an explanation of each type of blending.

  • Symbol

    Select one of the symbol types from the dropdown menu. This will be the shape of a new point or will change the shape of all points on the current points layer. The symbol property applies to all the points on a layer so you don’t need to have any points selected for it to have an effect. In fact, you cannot change the symbol for a single point on a layer and leave the rest the same.

  • Face and edge colors

    To change the point color properties from the GUI first select the points whose properties you want to change, otherwise you will just be initializing the property for the next point to add. Select the point you want to change, then click the thumbnail next to face color: or edge color: to select or create a color from the pallette.

  • Display text

    Check this box to turn display text on or off. Currently, text can be added to the points only programmatically and not through the GUI. Refer to the example Add points with multicolor text for more information.

  • 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, points slightly out of slice are rendered. Refer to Changing points size below for more information.

Other tools#

  • New points layer button

    Create a brand new empty points layer by clicking the New points layer button at the top of the layers list panel. The shape of the points layer is defined by the points inside it, as you add new points the shape will adjust as needed. The dimension of the new points layer will default to the largest dimension of any layer currently in the viewer, or to 2 if no other layers are present in the viewer.

  • 2D/3D button or Toggle ndisplay button

    All layers can be rendered in both 2D and 3D. The Toggle ndisplay button at the bottom of the left panel toggles between these 2 modes. When in 2D, the button looks like this: image: 2D/3D button, ready to switch to 3D mode. When in 3D, the button looks like this: image: 2D/3D button, ready to switch to 2D mode. You can also switch modes by pressing Ctrl+y.

    Note that when entering 3D rendering mode the GUI Add point, Delete selected points, and Select points tools are all disabled. Those options are supported only when viewing a layer using 2D rendering.

  • ctrl-c and ctrl-v (copying and pasting points)

    Copy and paste any selected points using ctrl-c and ctrl-v, respectively. If you have a multidimensional Points layer you can copy points from one slice to another by pasting them into the new slice. The coordinates of the points in the visible dimensions will be in the same place on the new slice as in the old slice, but the rest of the coordinates will be updated with the new slice values.

Controlling the points layer programmatically#

A simple example#

You can create a new viewer and add a set of points in one go using the napari.view_points() method, or if you already have an existing viewer, you can add points to it using viewer.add_points. The API of both methods is the same. In these examples we’ll mainly use add_points to overlay points onto on an existing image.

Each data point can have annotations associated with it using the Points.properties dictionary. These properties can be used to set the face and edge colors of the points. For example, when displaying points of different classes/types, one could automatically set the color of the individual points by their respective class/type. For more details on point properties, see Setting point edge and face color with properties below or the Point annotation tutorial.

In this example, we will overlay some points on the image of an astronaut:

import napari
import numpy as np
from skimage import data

viewer = napari.view_image(data.astronaut(), rgb=True)
points = np.array([[100, 100], [200, 200], [300, 100]])

points_layer = viewer.add_points(points, size=30)
Hide code cell source
from napari.utils import nbscreenshot

nbscreenshot(viewer, alt_text="3 points overlaid on an astronaut image")
3 points overlaid on an astronaut image

Arguments of view_points and add_points#

view_points() and add_points() accept the same layer-creation parameters.

help(napari.view_points)
Hide code cell output
Help on function view_points in module napari.view_layers:

view_points(data=None, *, ndim=None, features=None, feature_defaults=None, properties=None, text=None, symbol='o', size=10, border_width=0.05, border_width_is_relative=True, border_color='dimgray', border_color_cycle=None, border_colormap='viridis', border_contrast_limits=None, face_color='white', face_color_cycle=None, face_colormap='viridis', face_contrast_limits=None, out_of_slice_display=False, n_dimensional=None, name=None, metadata=None, scale=None, translate=None, rotate=None, shear=None, affine=None, opacity=1.0, blending='translucent', visible=True, cache=True, property_choices=None, experimental_clipping_planes=None, shading='none', canvas_size_limits=(2, 10000), antialiasing=1, shown=True, projection_mode='none', title='napari', ndisplay=2, order=(), axis_labels=(), 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 points layer.
    
    Parameters
    ----------
    data : array (N, D)
        Coordinates for N points in D dimensions.
    ndim : int
        Number of dimensions for shapes. When data is not None, ndim must be D.
        An empty points layer can be instantiated with arbitrary ndim.
    features : dict[str, array-like] or DataFrame
        Features table where each row corresponds to a point and each column
        is a feature.
    feature_defaults : dict[str, Any] or DataFrame
        The default value of each feature in a table with one row.
    properties : dict {str: array (N,)}, DataFrame
        Properties for each point. Each property should be an array of length N,
        where N is the number of points.
    property_choices : dict {str: array (N,)}
        possible values for each property.
    text : str, dict
        Text to be displayed with the points. If text is set to a key in properties,
        the value of that property will be displayed. Multiple properties can be
        composed using f-string-like syntax (e.g., '{property_1}, {float_property:.2f}).
        A dictionary can be provided with keyword arguments to set the text values
        and display properties. See TextManager.__init__() for the valid keyword arguments.
        For example usage, see /napari/examples/add_points_with_text.py.
    symbol : str, array
        Symbols to be used for the point markers. Must be one of the
        following: arrow, clobber, cross, diamond, disc, hbar, ring,
        square, star, tailed_arrow, triangle_down, triangle_up, vbar, x.
    size : float, array
        Size of the point marker in data pixels. If given as a scalar, all points are made
        the same size. If given as an array, size must be the same or broadcastable
        to the same shape as the data.
    border_width : float, array
        Width of the symbol border in pixels.
    border_width_is_relative : bool
        If enabled, border_width is interpreted as a fraction of the point size.
    border_color : str, array-like, dict
        Color of the point marker border. Numeric color values should be RGB(A).
    border_color_cycle : np.ndarray, list
        Cycle of colors (provided as string name, RGB, or RGBA) to map to border_color if a
        categorical attribute is used color the vectors.
    border_colormap : str, napari.utils.Colormap
        Colormap to set border_color if a continuous attribute is used to set face_color.
    border_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())
    face_color : str, array-like, dict
        Color of the point marker body. Numeric color values should be RGB(A).
    face_color_cycle : np.ndarray, list
        Cycle of colors (provided as string name, RGB, or RGBA) to map to face_color if a
        categorical attribute is used color the vectors.
    face_colormap : str, napari.utils.Colormap
        Colormap to set face_color if a continuous attribute is used to set face_color.
    face_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())
    out_of_slice_display : bool
        If True, renders points not just in central plane but also slightly out of slice
        according to specified point marker size.
    n_dimensional : bool
        This property will soon be deprecated in favor of 'out_of_slice_display'.
        Use that instead.
    name : str
        Name of the layer.
    metadata : dict
        Layer metadata.
    scale : tuple of float
        Scale factors for the layer.
    translate : tuple of float
        Translation values for the layer.
    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.
    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.
    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.
    opacity : float
        Opacity of the layer visual, between 0.0 and 1.0.
    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'}.
    visible : bool
        Whether the layer visual is currently being displayed.
    cache : bool
        Whether slices of out-of-core datasets should be cached upon retrieval.
        Currently, this only applies to dask arrays.
    shading : str, Shading
        Render lighting and shading on points. Options are:
    
        * 'none'
          No shading is added to the points.
        * 'spherical'
          Shading and depth buffer are changed to give a 3D spherical look to the points
    antialiasing: float
        Amount of antialiasing in canvas pixels.
    canvas_size_limits : tuple of float
        Lower and upper limits for the size of points in canvas pixels.
    shown : 1-D array of bool
        Whether to show each point.
        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.

Points data#

The input data to the points layer must be an NxD NumPy array containing the coordinates of N points in D dimensions. The ordering of these dimensions is the same as the ordering of the dimensions for image layers. This array is always accessible through the layer.data property and will grow or shrink as new points are either added or deleted.

Using the points properties dictionary#

The points layer can contain properties that annotate each point. Points.properties stores the properties in a dictionary where each key is the name of the property and the values are NumPy arrays with a value for each point (i.e., length N for N points in Points.data). As we will see below, we can use the values in a property to set the display properties of the points (e.g., face color or edge color). To see the points properties in action, please see the Point annotation tutorial.

Non-editable mode#

To disable editing the points layer, set the editable property of the layer to False.

When using 3D rendering the points layer cannot be edited.

3D rendering#

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 for example these points overlaid on an image in both 2D and 3D:

Adding, deleting, and selecting points#

To do this in the console, use code something like the example in Add points on nD shapes.

Changing points size#

Each point can have a different size. You can pass a list or 1-dimensional array of points through the size keyword argument to initialize the layer with points of different sizes. These sizes are then accessible through the size property. If you pass a single size then all points will get initialized with that size. Points can be pseudo-visualized as n-dimensional if the out_of_slice_display property is set to True. When True and viewing different slices of the layer, points will appear in the neighbouring slices to the ones in which they are located with a size scaled by the distance from their center to that slice. This feature can be especially useful when visualizing 2D slices of points that are located in a 3D volume.

The value of the size of the next point to be added can be found in the layer.current_size property. Note this property is different from layer.size which contains the current sizes of all the points.

Changing points edge and face color#

Individual points can each have different edge and face colors. You can initially set these colors by providing a list of colors to the edge_color or face_color keyword arguments respectively. The colors of each of the points are available as lists under the layer.edge_color and layer.face_color properties. Similar to the size and current_size properties, these properties are different from the layer.current_edge_color and layer.current_face_color properties that will determine the color of the next point to be added or any currently selected points.

Setting point edge and face color with properties#

Point edge and face colors can be set as a function of a property in Points.properties. There are two ways the values in Points.properties can be mapped to colors: (1) color cycles and (2) colormaps.

Color cycles are sets of colors that are mapped to categorical properties. The colors are repeated if the number of unique property values is greater than the number of colors in the color cycle.

Colormaps are a continuum of colors that are mapped to a continuous property value. The available colormaps are listed below (colormaps are from vispy). For guidance on choosing colormaps, see the matplotlib colormap docs.

list(napari.utils.colormaps.AVAILABLE_COLORMAPS)
['blue',
 'bop blue',
 'bop orange',
 'bop purple',
 'cyan',
 'gist_earth',
 'gray',
 'gray_r',
 'green',
 'hsv',
 'I Blue',
 'I Bordeaux',
 'I Forest',
 'I Orange',
 'I Purple',
 'inferno',
 'magenta',
 'magma',
 'PiYG',
 'plasma',
 'red',
 'turbo',
 'twilight',
 'twilight_shifted',
 'viridis',
 'yellow']

Setting edge or face color with a color cycle#

Here we will set the edge color of the markers with a color cycle on a property. To do the same for a face color, substitute face_color for edge_color in the example snippet below.

viewer = napari.view_image(data.astronaut(), rgb=True)
points = np.array([[100, 100], [200, 200], [300, 100]])
point_properties = {
    'good_point': np.array([True, True, False]),
    'confidence': np.array([0.99, 0.8, 0.2]),
}

points_layer = viewer.add_points(
    points,
    properties=point_properties,
    edge_color='good_point',
    edge_color_cycle=['magenta', 'green'],
    edge_width=0.5,
)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[6], line 8
      2 points = np.array([[100, 100], [200, 200], [300, 100]])
      3 point_properties = {
      4     'good_point': np.array([True, True, False]),
      5     'confidence': np.array([0.99, 0.8, 0.2]),
      6 }
----> 8 points_layer = viewer.add_points(
      9     points,
     10     properties=point_properties,
     11     edge_color='good_point',
     12     edge_color_cycle=['magenta', 'green'],
     13     edge_width=0.5,
     14 )

TypeError: add_points() got an unexpected keyword argument 'edge_color'
Hide code cell source
nbscreenshot(viewer, alt_text="3 points overlaid on an astronaut image, where the edge color of the points has been changed to a color cycle")

In the example above, the point_properties were provided as a dictionary with two properties: good_point and confidence. The values of each property are stored in a NumPy ndarray with length 3 since there were 3 coordinates provided in points. We set the edge color as a function of the good_point property by providing the keyword argument edge_color='good_point' to the viewer.add_points() method. The color cycle is set via the edge_color_cycle keyword argument, edge_color_cycle=['magenta', 'green']. The color cycle can be provided as a list of colors (as a list of strings or a (M x 4) array of M RGBA colors).

Setting edge or face color with a colormap#

In the example snippet below, we set the face color of the markers with a colormap on a property. To do the same for an edge color, substitute face for edge.

viewer = napari.view_image(data.astronaut(), rgb=True)
points = np.array([[100, 100], [200, 200], [300, 100]])
point_properties = {
    'good_point': np.array([True, True, False]),
    'confidence': np.array([0.99, 0.8, 0.2]),
}

points_layer = viewer.add_points(
    points,
    properties=point_properties,
    face_color='confidence',
    face_colormap='viridis',
)
Hide code cell source
nbscreenshot(viewer, alt_text="3 points overlaid on an astronaut image, where the face color of the points has been changed to a colormap")

In the example above, the point_properties were provided as a dictionary with two properties: good_point and confidence. The values of each property are stored in a NumPy ndarray with length 3 since there were 3 coordinates provided in points. We set the face color as a function of the confidence property by providing the keyword argument face_color='confidence' to the viewer.add_points() method. We set the colormap to viridis using the face_colormap keyword argument as face_colormap='viridis'.

Changing the points symbol#

The symbol for the points layer is a global property for the layer. All points on a layer must have the same symbol. You can set the symbol when loading the layer using the symbol keyword argument.

Putting it all together#

Here you can see an example of adding, selecting, deleting points, and changing their properties: