API reference
Class signatures, methods, and docstrings are rendered from the Python source. The layer and stats sections follow their modules' __all__ exports, so new public classes and plotting functions appear here on the next docs build.
Viewer and layout classes
Viewer
Bases: ViewerModel
Napari ndarray viewer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
title | string | The title of the viewer window. by default 'napari'. | 'napari-plot' |
show | bool | Whether to show the viewer after instantiation. by default True. | True |
_instances: WeakSet = WeakSet() class-attribute
_window: Window = Window(self, show=show) class-attribute instance-attribute
window: Window property
Get window
__init__(*, title='napari-plot', show=True, **kwargs: ty.Any)
close()
Close the viewer window.
close_all() -> int classmethod
Class method, Close all existing viewer instances.
This is mostly exposed to avoid leaking of viewers when running tests. As having many non-closed viewer can adversely affect performances.
It will return the number of viewer closed.
Returns:
| Type | Description |
|---|---|
int | number of viewer closed. |
export_figure(path: str | Path | None = None, *, scale_factor: float = 1, flash: bool = False, dpi: int | None = None) -> np.ndarray
Capture the full plotted data extent and restore the current view.
The raster image has shape (height, width, 4). Resolution starts at the current canvas size and is multiplied by scale_factor. Set dpi to change the output density relative to a 96 DPI canvas. An SVG or PDF path also writes the corresponding vector figure.
export_rois(rois: list[np.ndarray], paths: str | Path | list[str | Path] | None = None, scale: float | None = None) -> list[np.ndarray]
Capture each region's bounding box from four world-space (y, x) corners.
Pass a directory to save files as roi_0.png, roi_1.png and so on, or pass one destination path per region. Each capture starts at the current canvas resolution multiplied by scale.
export_vector(path: str | Path, *, scale_factor: float = 1, dpi: int | None = None) -> None
Export the full data extent as SVG or PDF, preserving line and text geometry.
screenshot(path: str | Path | None = None, *, size: tuple[int, int] | None = None, scale: float | None = None, canvas_only: bool = True, flash: bool = False) -> np.ndarray
Capture the current view as an RGBA array, optionally saving it to a file.
size is a (height, width) in physical pixels. size and scale apply to canvas-only captures.
show(*, block=False)
Resize, show, and raise the viewer window.
update_console(variables)
Update console's namespace with desired variables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
variables | dict, str or list/tuple of str | The variables to inject into the console's namespace. If a dict, a simple update is done. If a str, the string is assumed to have variable names separated by spaces. A list/tuple of str can also be used to give the variable names. If just the variable names are give (list/tuple/str) then the variable values looked up in the callers frame. | required |
ViewerModel
Bases: KeymapProvider, MousemapProviderPydantic, EventedModel
Viewer containing the rendered scene, layers, and controlling elements including dimension sliders, and control bars for color limits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
title | string | The title of the viewer window. | 'napari_plot' |
__non_evented_properties__ = EventedModel.__non_evented_properties__ | {'camera'} class-attribute instance-attribute
_brush_circle_overlay property
_canvas_size: tuple[int, int] property writable
_cell_colorbars: dict[tuple[int, int], ColorBar] = PrivateAttr(default_factory=dict) class-attribute instance-attribute
_cell_rects: dict[tuple[int, int], tuple[float, float, float, float]] = PrivateAttr(default_factory=dict) class-attribute instance-attribute
_colorbar_sources: dict[tuple[int, int] | None, n_layers.Layer] = PrivateAttr(default_factory=dict) class-attribute instance-attribute
_ctx: Context = create_context(self, max_depth=0) instance-attribute
_cursor_panel: str | None = PrivateAttr(None) class-attribute instance-attribute
_explicit_axis_labels: set[str] = PrivateAttr(default_factory=set) class-attribute instance-attribute
_layer_slicer: _LayerSlicer = PrivateAttr(default_factory=_LayerSlicer) class-attribute instance-attribute
_legend_source_layers: list[n_layers.Layer] = PrivateAttr(default_factory=list) class-attribute instance-attribute
_overlays: EventedDictNamespace property
_setting_axis_labels: bool = PrivateAttr(False) class-attribute instance-attribute
_sliced_extent_world: np.ndarray property
Return plot layer bounds as two world-coordinate (y, x) pairs.
_sliced_extent_world_augmented: np.ndarray property
Return plot bounds padded by half a sample step where applicable.
_text_overlay_names: list[str] = PrivateAttr(default_factory=list) class-attribute instance-attribute
autoscale: bool = True class-attribute instance-attribute
axis: Axis = Field(default_factory=Axis, frozen=True) class-attribute instance-attribute
camera: Camera property writable
Return the camera owned by the plot scene.
canvas: PlotCanvas = Field(default_factory=lambda: PlotCanvas(size=(400, 400), overlays=EventedDictNamespace()), frozen=True) class-attribute instance-attribute
colorbar: ColorBar = Field(default_factory=ColorBar, frozen=True) class-attribute instance-attribute
crosshair: CrosshairOverlay property
Crosshair overlay (hidden by default).
cursor: Cursor = Field(default_factory=Cursor, frozen=True) class-attribute instance-attribute
dims: Dims = Field(default_factory=Dims, frozen=True) class-attribute instance-attribute
drag_tool: DragTool = Field(default_factory=DragTool, frozen=True) class-attribute instance-attribute
grid_lines: GridLinesOverlay property
Text overlay
help: str = '' class-attribute instance-attribute
hover: HoverOverlay property
Hover readout overlay (hidden by default).
layers: LayerList = Field(default_factory=LayerList, frozen=True) class-attribute instance-attribute
legend: LegendOverlay property
Canvas legend overlay.
legend_visible: bool property
Whether the default legend overlay is visible.
margins: tuple[float, float] = (0.0, 0.0) class-attribute instance-attribute
mouse_over_canvas: bool = False class-attribute instance-attribute
scene: Scene = Field(default_factory=Scene, frozen=True) class-attribute instance-attribute
status: str | dict = 'Ready' class-attribute instance-attribute
text_overlay: TextOverlay property
Text overlay
theme: str = 'dark' class-attribute instance-attribute
title: str = 'napari-plot' class-attribute instance-attribute
tooltip: Tooltip = Field(default_factory=Tooltip, frozen=True) class-attribute instance-attribute
xlim: tuple[float, float] property writable
Current x limits in data coordinates and display order.
ylim: tuple[float, float] property writable
Current y limits in data coordinates and display order.
__hash__()
__init__(title='napari_plot')
__str__()
Simple string representation
_calc_status_from_cursor() -> tuple[str | dict, str] | None
_cell_extent(row: int, col: int) -> tuple[float, float, float, float]
Return the data bounds of a plot cell of a regular grid, from the camera's extent for shared axes.
_check_grid_cell(row: int, col: int) -> list[n_layers.Layer]
Return the layers of a plot cell of a regular grid, or raise if no such cell is shown.
_colorbar_events(layer: n_layers.Layer) -> tuple[EventEmitter, ...] staticmethod
_connect_legend_source_layer(layer: n_layers.Layer) -> None
_disconnect_colorbar_source(cell: tuple[int, int] | None) -> None
_disconnect_legend_source_layer(layer: n_layers.Layer) -> None
_extent_padding_px(layers: Sequence[n_layers.Layer]) -> float
Return the screen-pixel padding needed so lines and pixel-sized markers at the data edge are not clipped.
_get_positive_axis_min(axis: Literal['x', 'y'], fallback_max: float, *, layers: Sequence[n_layers.Layer] | None = None) -> float
Return the smallest positive layer coordinate on an axis.
_get_rect_extent(*, layers: Sequence[n_layers.Layer] | None = None, cell: PlotGridCell | None = None, margin: float | tuple[float, float] | None = None, use_camera_range: bool = True) -> tuple[float, float, float, float]
Get data extent, including image pixel edges and room for line widths and marker sizes.
_get_value_range_in_region(layers: Sequence[n_layers.Layer], axis: int, lo: float, hi: float, multiplier: float = 1.05) -> tuple[float, float] | None
Value range of layers over the data whose axis (0 = x, 1 = y) coordinate is in [lo, hi].
Used to fit the value axis of a joint marginal to what is visible along its shared axis. Zero is always included as a baseline and the data end(s) away from it are padded by multiplier - 1 of the range. Returns None when no layer has data in the range (or the data is flat at zero).
_get_x_range_extent_for_y(ymin: float, ymax: float, auto_scale: bool = True)
Calculate range for specified x-axis range.
_get_y_range_extent_for_x(xmin: float, xmax: float, ymin: float | None = 0, auto_scale: bool = True, y_multiplier: float = 1.0) -> tuple[float, float]
Calculate y-axis range for the specified x-axis range.
When auto_scale is enabled, the range is fitted to the data of layers that can report their y-axis extent within an x-axis window (e.g. line or centroids). If no such layer exists (e.g. scatter only), the current y-axis view is kept. ymin acts as a baseline that is always included and never padded, while the data ends are padded by y_multiplier - 1 of the range.
_grid_cells() -> dict[tuple[int, int], list[n_layers.Layer]]
Return the layers drawn in each plot cell of a regular grid (empty when the grid is off or joint).
_layer_help_from_mode(layer: n_layers.Layer) staticmethod
Update layer help text base on layer mode.
_on_active_layer(event)
Update viewer state for a new active layer.
_on_add_layer(event)
Connect new layer events.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event | :class:`napari.layers.Layer` | Layer to add. | required |
_on_autoscale_changed(_event: Event | None = None) -> None
_on_axis_label_changed(event: Event) -> None
_on_joint_metadata_change(_event: Event | None = None) -> None
_on_layer_list_event(event: Event) -> None
Update the data extent for layer-list events, and layer events re-emitted by it, that can change it.
Data and transform changes are handled by _on_layers_change; appearance changes (thumbnail, colour, ...) never move the data, and recomputing the extent for each of them made frequent data updates slow.
_on_layer_mode_change(event)
_on_layer_reload(event: Event) -> None
_on_layers_change(_event=None)
_on_legend_layers_change(_event: Event | None = None) -> None
Refresh automatic legend state after layer collection changes.
_on_legend_source_change(event: Event | None = None) -> None
Refresh the synced legend from its configured source.
_on_remove_layer(event)
Disconnect old layer events.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event | Event | Event which will remove a layer. | required |
Returns:
| Name | Type | Description |
|---|---|---|
layer | :class:`napari.layers.Layer` or list | The layer that was added (same as input). |
_on_update_extent(_event=None)
Update data extent when there has been a change to the list of layers
_on_update_tool(event)
Update drag method based on currently active tool.
_pixel_mapper() -> PixelMapper | None
Map data coordinates to canvas pixels, or None before the canvas has a size.
_publish_cell_rect(cell: tuple[int, int], rect: tuple[float, float, float, float] | None) -> None
Store the own limits of a grid cell (None when it has none) and emit cell_rect when they changed.
_refresh_legend_source_connections(_event: Event | None = None) -> None
Reconnect live legend source listeners.
_sanitize_log_extent(lower: float, upper: float, axis: Literal['x', 'y'], *, scale: AxisScale | None = None, layers: Sequence[n_layers.Layer] | None = None) -> tuple[float, float]
Return positive limits for a logarithmic axis.
_select_data(vertices: np.ndarray, *, cell: tuple[int, int] | None = None) -> None
Replace the selected indices in the visible, selected plot layers.
_set_axis_limits(axis: Literal['x', 'y'], value: tuple[float, float] | None) -> None
Apply one axis's data limits; descending limits invert the displayed axis.
_sync_colorbar(_event: Event | None = None) -> None
Copy the colormap and contrast limits of the source layer to the colorbar.
_update_async(event: Event) -> None
Set layer slicer to force synchronous if async is disabled.
_update_axis_labels(_event: Event | None = None) -> None
Inherit layer metadata while preserving explicit plot axis labels.
_update_cursor(event)
Set the viewer cursor with the event.cursor string.
_update_cursor_size(event)
Set the viewer cursor_size with the event.cursor_size int.
_update_hover(_event: Any = None) -> None
Move the crosshair and update the hover readout for the cursor position.
_update_layers(*, layers=None)
Updates the contained layers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
layers | list of napari.layers.Layer | List of layers to update. If none provided updates all. | None |
_update_mouse_pan(event)
Set the viewer interactive mouse panning
_update_mouse_zoom(event)
Set the viewer interactive mouse zoom
_valid_theme(v) classmethod
_validate_margins(value: tuple[float, float]) -> tuple[float, float] classmethod
add_image(data=None, *, channel_axis=None, affine=None, axis_labels=None, attenuation=0.05, blending=None, cache=True, colormap=None, contrast_limits=None, custom_interpolation_kernel_2d=None, depiction='volume', experimental_clipping_planes=None, gamma=1.0, interpolation2d='nearest', interpolation3d='linear', iso_threshold=None, metadata=None, multiscale=None, name=None, opacity=1.0, plane=None, projection_mode='none', rendering='mip', rgb=None, rotate=None, scale=None, shear=None, translate=None, units=None, visible=True) -> n_layers.Image | list[n_layers.Image]
Add one or more Image layers to the layer list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | array or list of array | Image data. Can be N >= 2 dimensional. If the last dimension has length 3 or 4 can be interpreted as RGB or RGBA if rgb is | None |
channel_axis | int | Axis to expand image along. If provided, each channel in the data will be added as an individual image layer. In channel_axis mode, other parameters MAY be provided as lists. The Nth value of the list will be applied to the Nth channel in the data. If a single value is provided, it will be broadcast to all Layers. All parameters except data, rgb, and multiscale can be provided as list of values. If a list is provided, it must be the same length as the axis that is being expanded as channels. | None |
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 | None |
axis_labels | tuple of str | Dimension names of the layer data. If not provided, axis_labels will be set to (..., 'axis -2', 'axis -1'). | None |
attenuation | float or list of float | Attenuation rate for attenuated maximum intensity projection. | 0.05 |
blending | str or list of 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 {'translucent', 'translucent_no_depth', 'additive', 'minimum', 'opaque'}. | None |
cache | bool or list of bool | Whether slices of out-of-core datasets should be cached upon retrieval. Currently, this only applies to dask arrays. | True |
colormap | str, napari.utils.Colormap, tuple, dict, list or list of these types | Colormaps to use for luminance images. If a string, it can be the name of a supported colormap from vispy or matplotlib or the name of a vispy color or a hexadecimal RGB color representation. If a tuple, the first value must be a string to assign as a name to a colormap and the second item must be a Colormap. If a dict, the key must be a string to assign as a name to a colormap and the value must be a Colormap. | None |
contrast_limits | list(2) | Intensity value limits to be used for determining the minimum and maximum colormap bounds for luminance images. If not passed, they will be calculated as the min and max intensity value of the image. | None |
custom_interpolation_kernel_2d | ndarray | Convolution kernel used with the 'custom' interpolation mode in 2D rendering. | None |
depiction | str or list of str | 3D Depiction mode. Must be one of {'volume', 'plane'}. The default value is 'volume'. | 'volume' |
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. | None |
gamma | float or list of float | Gamma correction for determining colormap linearity; defaults to 1. | 1.0 |
interpolation2d | str or list of str | Interpolation mode used by vispy for rendering 2d data. Must be one of our supported modes. (for list of supported modes see Interpolation enum) 'custom' is a special mode for 2D interpolation in which a regular grid of samples is taken from the texture around a position using 'linear' interpolation before being multiplied with a custom interpolation kernel (provided with 'custom_interpolation_kernel_2d'). | 'nearest' |
interpolation3d | str or list of str | Same as 'interpolation2d' but for 3D rendering. | 'linear' |
iso_threshold | float or list of float | Threshold for isosurface. | None |
metadata | dict or list of dict | Layer metadata. | None |
multiscale | bool | Whether the data is a multiscale image or not. Multiscale data is represented by a list of array-like image data. If not specified by the user and if the data is a list of arrays that decrease in shape, then it will be taken to be multiscale. The first image in the list should be the largest. Please note multiscale rendering is only supported in 2D. In 3D, only the lowest resolution scale is displayed. | None |
name | str or list of str | Name of the layer. | None |
opacity | float or list | Opacity of the layer visual, between 0.0 and 1.0. | 1.0 |
plane | dict or SlicingPlane | Properties defining plane rendering in 3D. Properties are defined in data coordinates. Valid dictionary keys are {'position', 'normal', 'thickness', and 'enabled'}. | None |
projection_mode | str | How data outside the viewed dimensions, but inside the thick Dims slice will be projected onto the viewed dimensions. Must fit to cls._projectionclass | 'none' |
rendering | str or list of str | Rendering mode used by vispy. Must be one of our supported modes. If a list then must be same length as the axis that is being expanded as channels. | 'mip' |
rgb | bool | Whether the image is RGB or RGBA if rgb. If not specified by user, but the last dimension of the data has length 3 or 4, it will be set as | None |
rotate | float, 3-tuple of float, n-D array or list. | 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. | None |
scale | tuple of float or list of tuple of float | Scale factors for the layer. | None |
shear | 1-D array or list. | A vector of shear values for an upper triangular n-D shear matrix. | None |
translate | tuple of float or list of tuple of float | Translation values for the layer. | None |
units | tuple of str or pint.Unit | Units of the layer data in world coordinates. If not provided, the default units are assumed to be pixels. | None |
visible | bool or list of bool | Whether the layer visual is currently being displayed. | True |
Returns:
| Name | Type | Description |
|---|---|---|
layer | :class:`napari.layers.Image` or list | The newly-created image layer or list of image layers. |
add_layer(layer: n_layers.Layer) -> n_layers.Layer
Add a layer to the viewer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
layer | :class:`napari.layers.Layer` | Layer to add. | required |
Returns:
| Name | Type | Description |
|---|---|---|
layer | :class:`napari.layers.Layer` or list | The layer that was added (same as input). |
add_text_overlay(text: str, position: str = 'top_left', name: str | None = None, **kwargs: Any) -> TextOverlay
Show text at a corner or edge of the plot area (e.g. a statistics box), unaffected by zooming.
Unlike text_overlay (used as the plot title), any number of these can be added. position is a canvas position such as top_left or bottom_right; other keyword arguments (color, font_size, box, ...) are passed to napari's TextOverlay. Adding text with the name of an earlier one replaces it.
annotate(text: str, xy: tuple[float, float], xytext: tuple[float, float] | None = None, *, arrow_color: Any = None, arrow_width: float = 1.0, **kwargs: Any) -> np_layers.Text
Label a point and draw an arrow from xytext when it differs from xy.
axhline(y: float = 0, **kwargs: Any) -> np_layers.InfLine
Add a horizontal reference line at y.
axhspan(ymin: float, ymax: float, **kwargs: Any) -> np_layers.Region
Shade a horizontal span between two y coordinates.
axvline(x: float = 0, **kwargs: Any) -> np_layers.InfLine
Add a vertical reference line at x.
axvspan(xmin: float, xmax: float, **kwargs: Any) -> np_layers.Region
Shade a vertical span between two x coordinates.
cell_rect(row: int, col: int) -> tuple[float, float, float, float]
Return the (xmin, xmax, ymin, ymax) limits shown in a plot cell of a regular grid.
Shared axes show the limits of the viewer's camera; an independent axis shows the cell's own limits.
clear_canvas()
Remove all layers from the canvas
clear_colorbar(*, cell: tuple[int, int] | None = None) -> None
Hide the global or per-cell colorbar and disconnect its source.
clear_legend() -> None
Clear and hide the default legend without removing its canvas visual.
colorbar_for_cell(row: int, col: int) -> ColorBar
Return the independent colorbar settings for the given grid cell.
errorbar(x: ArrayLike, y: ArrayLike, *, xerr: ArrayLike | None = None, yerr: ArrayLike | None = None, **kwargs: Any) -> np_layers.ErrorBar
Draw intervals from scalar, per-point, or (2, N) lower and upper offsets.
export_csv(layer: n_layers.Layer | str, path: str | Path) -> None
Write the source data of a layer (or named layer) to a CSV file.
fill_between(x: ArrayLike, y1: ArrayLike, y2: ArrayLike = 0, **kwargs: Any) -> np_layers.Band
Fill between two bounds on a shared x grid. Either bound can be a scalar.
fill_betweenx(y: ArrayLike, x1: ArrayLike, x2: ArrayLike = 0, **kwargs: Any) -> np_layers.Band
Fill between two bounds on a shared y grid. Either bound can be a scalar.
hbar(y: ArrayLike, length: ArrayLike | None = None, *, baseline: float | None = None, width: ArrayLike | None = None, **kwargs: Any) -> np_layers.Bar
Add horizontal bars. Use width for thickness when length is provided.
hist(values: ArrayLike, bins: int | str | ArrayLike = 10, *, range: tuple[float, float] | None = None, weights: ArrayLike | None = None, density: bool = False, baseline: float = 0.0, orientation: Literal['vertical', 'horizontal'] = 'vertical', **kwargs: Any) -> np_layers.Bar
Add a histogram with NumPy binning and support for uneven bin widths.
hover_info(x: float, y: float) -> HoverInfo | None
Describe the data point under the data position (x, y), or None when no layer has one.
Every visible plot layer reports its point under the cursor; the one vertically closest to the cursor on screen is the primary point, and the others are listed as rows.
imshow(data: Any, **kwargs: Any) -> n_layers.Image | list[n_layers.Image]
Display an image using the standard image-layer API.
json(**kwargs)
Serialize to json.
load_session(path: str | Path) -> list[n_layers.Layer]
Replace the current plot with a saved session and return the restored layers.
model_dump(**kwargs) -> dict
Convert to a dictionary.
open(path: str | Path | Sequence[str | Path], *, stack: bool | list[list[str]] = False, plugin: str | None = None, layer_type: str | None = None, **kwargs: Any) -> list[n_layers.Layer]
Open saved sessions, two-column CSV plots, or files supported by napari readers.
plot(x: Any, y: Any | None = None, **kwargs: Any) -> np_layers.Line
Add a line from plot(y) or plot(x, y) coordinates.
rectangle(xy: tuple[float, float], width: float, height: float, **kwargs: Any) -> np_layers.Rectangles
Add a rectangle from its lower-left corner and dimensions.
refresh_legend_from_layers() -> LegendOverlay
Refresh the default legend without changing its visual style.
refresh_legend_from_source() -> LegendOverlay
Refresh a Points-derived legend from its configured source.
remove_text_overlays() -> None
Remove every text added with add_text_overlay.
reset_current_y_view(_event=None)
Reset y-axis for current selection.
reset_plot() -> None
Remove all layers and reset what plots leave behind.
This covers categorical axes (incl. tick rotation and thinning), log scales, fixed ranges, legend, colorbar and text overlays.
reset_view(_event: Event | None = None, *, margin: float | tuple[float, float] | None = None, use_camera_range: bool = True) -> None
Fit the view to the data with optional fractional margins and camera range overrides.
reset_x_view(_event=None)
Reset the camera view, but only in the y-axis dimension
reset_y_view(_event=None)
Reset the camera view, but only in the y-axis dimension
save_session(path: str | Path) -> None
Save the current plot settings and layer data to a portable session archive.
scatter(x: Any, y: Any | None = None, **kwargs: Any) -> np_layers.Scatter
Add scatter points from scatter(y) or scatter(x, y) coordinates.
set_cell_rect(row: int, col: int, xmin: float, xmax: float, ymin: float, ymax: float) -> None
Set the limits shown in a plot cell of a regular grid.
The limits of a shared axis go to the viewer's camera, so every cell sharing that axis follows.
set_colorbar_from_layer(layer: n_layers.Layer | str, label: str = '', *, cell: tuple[int, int] | None = None, position: Literal['right', 'bottom'] | None = None, orientation: Literal['vertical', 'horizontal'] | None = None, norm: Literal['linear', 'log'] | None = None) -> ColorBar
Show the continuous color scale of an image or scatter layer, optionally in a grid cell.
set_legend(entries: LegendInput, *, visible: bool = True, position: str = 'top_right', text_color: LegendColorLike = None, font_size: float | None = None, marker_size: float = 10.0, row_spacing: float = 9.0, padding: float = 6.0, background_color: LegendColorLike = None, border_color: LegendColorLike = None, border_width: float = 1.0, title: str = '', ncols: int = 1, outside: bool = False) -> LegendOverlay
Configure the default canvas legend from explicit entries.
set_legend_auto_sync(enabled: bool = True) -> LegendOverlay
Enable or disable automatic legend source updates.
set_legend_from_layers(*, sync: bool = True, visible: bool = True, position: str = 'top_right', text_color: LegendColorLike = None, font_size: float | None = None, marker_size: float = 10.0, row_spacing: float = 9.0, padding: float = 6.0, background_color: LegendColorLike = None, border_color: LegendColorLike = None, border_width: float = 1.0, title: str = '', ncols: int = 1, outside: bool = False) -> LegendOverlay
Configure the default legend from visible plot layers.
set_legend_from_points(layer: str | n_layers.Points, *, label_property: str = 'label', color_source: str = 'face', marker_source: str = 'symbol', group_by_style: bool = True, sync: bool = False, visible: bool = True, **style: Any) -> LegendOverlay
Configure the default legend from categorized Points data.
set_legend_visible(visible: bool) -> None
Set default legend visibility.
set_x_view(xmin: float, xmax: float, ymin: float = 0, y_multiplier: float = 1.05, auto_scale: bool = True)
Set view on specified x-axis
set_y_view(ymin: float, ymax: float)
Set view on specified y-axis
stackplot(x: ArrayLike, *ys: ArrayLike, baseline: float = 0.0, **kwargs: Any) -> np_layers.Areas
Fill successive cumulative bands, with one row of values per band.
stem(x: ArrayLike, y: ArrayLike | None = None, *, baseline: float = 0.0, **kwargs: Any) -> np_layers.Centroids
Draw stems from a shared baseline to y values.
text(x: ArrayLike, y: ArrayLike, text: str | list[str], **kwargs: Any) -> np_layers.Text
Add one label or a sequence of labels at xy coordinates.
update_extents(_event=None)
Reset y-axis for current selection.
update_status_from_cursor()
Update the status and tooltip from the cursor position.
vbar(x: ArrayLike, height: ArrayLike | None = None, *, baseline: float | None = None, **kwargs: Any) -> np_layers.Bar
Add vertical bars from values or explicit x positions and heights.
JointGrid
Arrange a main plot and optional top and right marginals on one viewer.
ratio controls the size of the main panel relative to the marginals, unless size sets the thickness of the marginals in screen pixels. The top shares the main x axis and the right shares the main y axis. With autoscale, the value axis of each marginal follows the data visible in the shared range and interaction in a marginal only changes its shared axis (see PlotGridCanvas).
layers: list[Layer] = [] instance-attribute
viewer = viewer instance-attribute
__init__(viewer: ViewerModel, *, top: bool = True, right: bool = True, ratio: float = 5, size: int | None = None, autoscale: bool = False) -> None
_validate_panel(panel: JointPanel) -> None
add_layer(layer: Layer, *, panel: JointPanel = 'joint') -> Layer
Add or move a layer to a panel and return it.
set_axis_labels(x_var: str | None = None, y_var: str | None = None, *, panel: JointPanel = 'joint', visible: bool | None = None) -> JointGrid
Set one panel's axis labels and optionally hide or show them.
Use y_var for the top margin and x_var for the right margin. Toggling visible preserves the label text, ticks, and axis lines.
set_tick_formatter(formatter: Callable[..., str] | None, *, panel: Literal['top', 'right']) -> JointGrid
Format the value-axis ticks of a marginal (y in the top panel, x in the right panel).
None restores the default format. The shared axes use the viewer's axis formatters.
napari widgets
NapariPlotWidget
Bases: QWidget
Create instance of napari-plot Viewer.
qt_viewer = QtViewer(self.viewer_plot, parent=parent) instance-attribute
viewer = napari_viewer instance-attribute
viewer_plot = ViewerModelPlot() instance-attribute
__init__(napari_viewer)
_update_theme(event=None) -> None
Apply the host napari theme to the embedded plotting widget.
closeEvent(event) -> None
Disconnect host-viewer events before closing the widget.
ScatterPlotWidget
Bases: NapariPlotWidget
Widget which enables displaying scatter plot of two layers.
The widget compares the values in the currently displayed slices. Selected images must therefore have identical displayed-slice shapes.
current_slice_label: str property
Human-readable coordinates of the current non-displayed dimensions.
layers: list[Image] = [] instance-attribute
scatter_layer = self.viewer_plot.add_scatter(None, border_color='orange') instance-attribute
__init__(napari_viewer: napari.viewer.Viewer)
_check_layers(layers: list) -> bool staticmethod
Check whether layers of correct type.
_displayed_slice(layer: Image) -> np.ndarray staticmethod
Return the image values currently displayed by napari.
_scatter_data(layers: list[Image]) -> np.ndarray classmethod
Build paired scatter coordinates from two displayed image slices.
_set_layers(layers: list[Image]) -> None
Replace selected layers and update their data-event connections.
closeEvent(event) -> None
Close event.
connect_events(state: bool = True) -> None
Connect events.
on_update_layers(event=None)
Update layer selection.
on_update_scatter(event: Any = None) -> None
Update the scatter plot from the selected displayed image slices.
Plot layers
layers
Layers are the viewable objects that can be added to a viewer.
Custom layers must inherit from Layer and pass along the visual node <http://vispy.org/scene.html#module-vispy.scene.visuals>_ to the super constructor.
Areas
Bases: BaseLayer
Fill many regions, each between a lower and an upper curve.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | sequence of array-like | One | None |
orientation | str or AreasOrientation | Axis along which | VERTICAL |
fill_color | color or sequence of colors | Fill color shared by all areas or supplied per area. | 'white' |
border_color | color or sequence of colors | Outline color shared by all areas or supplied per area. | 'dimgray' |
border_width | float | Outline width in screen pixels. Zero hides outlines. | 1.0 |
border_color: np.ndarray property writable
One RGBA outline color per area.
border_width: float property writable
Outline width in screen pixels.
color: np.ndarray property writable
Compatibility alias for the fill colors.
data: list[np.ndarray] property writable
Areas as a list of (t, lo, hi) arrays.
fill_color: np.ndarray property writable
One RGBA fill color per area.
orientation: AreasOrientation property writable
Axis along which the shared t coordinate runs.
stream(data: Sequence[ArrayLike]) -> None
Rapidly replace the areas, e.g. for live updates.
Only the stream event is emitted: the areas are redrawn, but the viewer's data extent and the thumbnail are not updated. The colors are kept when the number of areas is unchanged.
Band
Bases: BaseLayer
Fill between two curves along a shared axis.
Data contains (x, y1, y2) rows, or (y, x1, x2) rows for horizontal bands. The first column must be strictly monotonic. NaN in either bound creates a gap. Curves may cross.
data: np.ndarray property writable
Band coordinates as (x, y1, y2) rows.
fill_color: np.ndarray property writable
Fill color as one RGBA value.
orientation: Literal['vertical', 'horizontal'] property
Return which coordinate the band uses for its shared grid.
Bar
Bases: BaseLayer
Layer rendering finite horizontal or vertical bars.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | array - like | Either one value per bar or | None |
orientation | str or BarOrientation | Whether values extend vertically or horizontally from | VERTICAL |
baseline | float | Shared value from which every bar begins. | 0.0 |
width | float | Bar width in data coordinates. | 0.8 |
fill_color | color or sequence of colors | Fill color shared by all bars or supplied per bar. | 'white' |
border_color | color or sequence of colors | Border color shared by all bars or supplied per bar. | 'dimgray' |
border_width | float | Border width in screen pixels. | 1.0 |
baseline: float property writable
Shared start value for all bars.
baselines: np.ndarray property
Per-bar start values (third data column, or the shared baseline).
border_color: np.ndarray property writable
One RGBA border color per bar.
border_width: float property writable
Border width in screen pixels.
color: np.ndarray property writable
Compatibility alias for the representative fill colors.
data: np.ndarray property writable
Bar (position, value) rows.
fill_color: np.ndarray property writable
One RGBA fill color per bar.
orientation: BarOrientation property writable
Direction in which bars extend from the baseline.
positions: np.ndarray property
Bar center positions.
selected_data: set[int] property writable
Indices of selected bars.
values: np.ndarray property
Bar endpoint values.
width: float property writable
Bar width in data coordinates.
widths: np.ndarray property
Per-bar widths (fourth data column, or the shared width).
remove_selected() -> None
Remove selected bars and their per-bar colors.
Centroids
Bases: _SelectableLayer
Centroids layer
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | array | Coordinates for N points in 2 dimensions. If array has shape (N, 2) then its assume that its the position and upper value and the lower value is assumed to be zero. If array has shape (N, 3) then its assumed that its the position, lower value and upper value. X-axis and Y-axis values are inferred based on the orientation attribute. Coordinates for N points in 2 dimensions. | required |
orientation | str or Orientation | If string, can be | 'vertical' |
color | (str, array - like) | If string can be any color name recognized by vispy or hex value if starting with | (1.0, 1.0, 1.0, 1.0) |
width | float | Width of the line in pixel units. | 2 |
method | str or Method | Rendering method. Either | 'gl' |
name | str | Name of the layer. | None |
metadata | dict | Layer metadata. | None |
scale | tuple of float | Scale factors for the layer. | None |
translate | tuple of float | Translation values for the layer. | None |
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. | None |
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. | None |
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 | None |
opacity | float | Opacity of the layer visual, between 0.0 and 1.0. | 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', 'translucent_no_depth', and 'additive'}. | 'translucent' |
visible | bool | Whether the layer visual is currently being displayed. | True |
color: np.ndarray property writable
Get color
data: np.ndarray property writable
Return data.
method: Method | str property writable
Get method.
orientation: Orientation property writable
Orientation of the centroids layer.
width: float property writable
Get width.
update_color(index: int, color: np.ndarray) -> None
Update color of single line.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index | int | Index of the line to update the color of. | required |
color | str | tuple | ndarray | Color of the line. | required |
ErrorBar
Bases: BaseLayer
Draw error intervals around a set of points.
Data contains (x, y, x_minus, x_plus, y_minus, y_plus) rows. Offsets are nonnegative and measured in axis units. A pair of NaNs omits that axis. Width and cap size are in screen pixels.
cap_size: float property writable
Full length of the caps in screen pixels. Zero hides caps.
color: np.ndarray property writable
Color of stems and caps as one RGBA value.
data: np.ndarray property writable
Point centers followed by the lower and upper offsets for x and y.
width: float property writable
Thickness of stems and caps in screen pixels.
InfLine
Bases: BaseLayer
InfLine layer
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | Coordinates for N points in 2 dimensions. | None | |
orientation | str or Orientation or list of str or list of Orientation | If string, can be | 'vertical' |
color | (str, array - like) | If string can be any color name recognized by vispy or hex value if starting with | (1.0, 1.0, 1.0, 1.0) |
width | float | Width of the line in pixel units. | 1 |
line_style | str or LineStyle | Style of every line: | 'solid' |
name | str | Name of the layer. | None |
metadata | dict | Layer metadata. | None |
scale | tuple of float | Scale factors for the layer. | None |
translate | tuple of float | Translation values for the layer. | None |
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. | None |
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. | None |
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 | None |
opacity | float | Opacity of the layer visual, between 0.0 and 1.0. | 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', 'translucent_no_depth', and 'additive'}. | 'translucent' |
visible | bool | Whether the layer visual is currently being displayed. | True |
color: np.ndarray property writable
Get color
current_color: np.ndarray property writable
Get current color.
data: np.ndarray property writable
Return data
line_style: LineStyle property writable
Style of every line: solid, dashed or dotted.
mode: str property writable
str: Interactive mode
Interactive mode. The normal, default mode is PAN_ZOOM, which allows for normal interactivity with the canvas.
In MOVE the region is moved to new location
n_inflines: int property
Get number of infinite lines.
orientation: list[Orientation] property
Return list of orientations.
selected_data: set[int] property writable
set: set of currently selected points.
width: float property writable
Get width
add(data, *, orientation='vertical', color=None, z_index=None)
Add lines to the current layer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | Array | Tuple(float, str) | List[float | Tuple(float, str)] | Tuple(List[float], str) | List of line data, where each element is either position or a tuple containing (position, orientation). When orientation is present, it overrides keyword argument | required |
orientation | string | list | String of orientation type, must be one of "{'vertical', 'horizontal'}. If list is supplied it must be the same length as the length of | 'vertical' |
color | str | tuple | list | If string can be any color name recognized by vispy or hex value if starting with | None |
z_index | int | list | Specifier of z order priority. Lines with higher z order are displayed on top of others. If a list is supplied it must be the same length as the length of | None |
move(index: int, pos: float, orientation=None, finished: bool = False)
Move line to new location.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index | int | Index of the line. | required |
pos | float | New position along the x-axis or y-axis. | required |
orientation | str or Orientation | String of orientation type, must be one of "{'vertical', 'horizontal'}. If one is not provided, only the position is changed. | None |
finished | bool | Flag to indicate whether the | False |
remove_selected() -> None
Remove any selected shapes.
Line
Bases: _SelectableLayer
Line layer
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | array(N, 2) | Coordinates for N points in 2 dimensions. | required |
color | (str, array - like) | If string can be any color name recognized by vispy or hex value if starting with | (1.0, 1.0, 1.0, 1.0) |
width | float | Width of the line in pixel units. | 2 |
method | str or Method | Rendering method. Either | 'gl' |
dashes | sequence of float | Alternating visible and hidden lengths in multiples of line width. Dashed lines use VisPy's antialiased rendering method. | None |
name | str | Name of the layer. | None |
metadata | dict | Layer metadata. | None |
scale | tuple of float | Scale factors for the layer. | None |
translate | tuple of float | Translation values for the layer. | None |
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. | None |
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. | None |
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 | None |
opacity | float | Opacity of the layer visual, between 0.0 and 1.0. | 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', 'translucent_no_depth', and 'additive'}. | 'translucent' |
visible | bool | Whether the layer visual is currently being displayed. | True |
color: np.ndarray property writable
Get color.
dashes: tuple[float, ...] | None property writable
Return the dash pattern, or None for a solid line.
data: np.ndarray property writable
Return data.
method: Method | str property writable
Get method
width: float property writable
Get width
x: np.ndarray property writable
Return x-axis array.
y: np.ndarray property writable
Return y-axis array.
MultiLine
Bases: _SelectableLayer
MultiLine layer
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | dict of xs and ys array (N, 1), (N, D) | Coordinates for N points in 2 dimensions. | required |
color | (str, array - like) | If string can be any color name recognized by vispy or hex value if starting with | (1.0, 1.0, 1.0, 1.0) |
width | float | Width of the line in pixel units. | 2 |
method | str or Method | Rendering method. Either | 'gl' |
name | str | Name of the layer. | None |
metadata | dict | Layer metadata. | None |
scale | tuple of float | Scale factors for the layer. | None |
translate | tuple of float | Translation values for the layer. | None |
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. | None |
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. | None |
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 | None |
opacity | float | Opacity of the layer visual, between 0.0 and 1.0. | 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', 'translucent_no_depth', and 'additive'}. | 'translucent' |
visible | bool | Whether the layer visual is currently being displayed. | True |
color: np.ndarray property writable
Get color.
current_color property writable
Get current color.
data property writable
Return data
method: Method property writable
Get method
width: float property writable
Get width
add(data, *, color=None)
Add line(s) to the container.
stream(data, full_update: bool = False)
Rapidly update data on the layer without doing additional checks.
This method will simply replace the existing data with new without checking e.g. the number of lines or the number of colors. This validation falls to the user to ensure that data is correct.
This method only triggers the stream event which will update the line data without updating line connections or colors.
update_color(index: int, color: np.ndarray)
Update color of single line.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index | int | Index of the line to update the color of. | required |
color | str | tuple | ndarray | Color of the line. | required |
Rectangles
Bases: BaseLayer
Display 2D rectangle outlines with optional center markers and labels.
Pass [x, y] centers with height and width in data units. Dimensions can be scalars or arrays with one value per rectangle. Alternatively, pass [x, y, height, width] rows as the first argument.
Outlines use one outline_width in screen pixels and accept shared or per-rectangle outline_color. Markers use Scatter symbols and accept shared or per-rectangle marker_size in screen pixels, marker_color, and marker_symbol. Pass one literal string per rectangle as text. Labels use a shared text_size in screen points (None uses the application setting), text_color, and an [x, y] text_offset in data units.
Set mode to "add" to draw a rectangle by dragging. In "edit" mode, drag an existing rectangle to move it, or Shift-drag to resize it.
centers: np.ndarray property
Read-only [x, y] rectangle centers.
data: np.ndarray property writable
Read-only [x, y, height, width] rows. Assign new rows to update.
marker_color: np.ndarray property writable
Shared RGBA marker color or one RGBA row per rectangle.
marker_size: float | np.ndarray property writable
Marker diameters in screen pixels.
marker_symbol: str | np.ndarray property writable
Scatter symbol name or one name per marker.
outline_color: np.ndarray property writable
Shared RGBA outline color or one RGBA row per rectangle.
outline_width: float property writable
Shared outline width in screen pixels.
show_markers: bool property writable
Whether to mark the rectangle centers.
show_rectangles: bool property writable
Whether to draw the rectangle outlines.
show_text: bool property writable
Whether to draw the supplied labels.
text: np.ndarray | None property writable
Literal label strings, or None when no labels are supplied.
text_color: np.ndarray property writable
Shared RGBA label color.
text_offset: np.ndarray property writable
Shared [x, y] label offset from the centers in data units.
text_size: float | None property writable
Font size in screen points, or None to use the application setting.
set_data(centers: ArrayLike, height: ArrayLike, width: ArrayLike) -> None
Replace geometry from [x, y] centers and scalar or per-row dimensions.
Region
Bases: BaseLayer
Regions layer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | list of array-like or list of tuple of array-like and str or list of tuple of array-like and Orientation | Layer can be initialized by providing list of arrays, list of arrays + orientation of region where each array has two elements (start position, end position). | None |
orientation | str or list of str or list of Orientation | List of orientations for each provided region. If orientations are not provided, they will be inferred directly from | 'vertical' |
color | (str, array - like) | If string can be any color name recognized by vispy or hex value if starting with | (1.0, 1.0, 1.0, 1.0) |
z_index | int or list | Specifier of z order priority. Regions with higher z order are displayed on top of others. If a list is supplied it must be the same length as the length of | 0 |
name | str | Name of the layer. | None |
metadata | dict | Layer metadata. | None |
scale | tuple of float | Scale factors for the layer. | None |
translate | tuple of float | Translation values for the layer. | None |
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. | None |
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. | None |
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 | None |
opacity | float | Opacity of the layer visual, between 0.0 and 1.0. | 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', 'translucent_no_depth', and 'additive'}. | 'translucent' |
visible | bool | Whether the layer visual is currently being displayed. | True |
color: np.ndarray property writable
(N x 4) np.ndarray: Array of RGBA colors for each region.
current_color: np.ndarray property writable
Return current color.
data: np.ndarray property writable
Return data
mode: str property writable
str: Interactive mode
Interactive mode. The normal, default mode is PAN_ZOOM, which allows for normal interactivity with the canvas.
In MOVE the region is moved to new location
n_regions: int property
Get number of regions.
orientation: list[Orientation] property
Orientation of the infinite region.
selected_data: set[int] property writable
set: set of currently selected points.
z_index: list[int] property writable
list of int: z_index for each shape.
accept() -> None
Emit accept event
add(data, *, orientation='vertical', color=None, z_index=None)
Add shapes to the current layer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | Array | Tuple(Array, str) | List[Array | Tuple(Array, str)] | Tuple(List[Array], str) | List of shape data, where each element is either an (N, D) array of the N vertices of a shape in D dimensions or a tuple containing an array of the N vertices and the shape_type string. When a shape_type is present, it overrides keyword arg shape_type. Can be an 3-dimensional array if each shape has the same number of vertices. | required |
orientation | string | list | String of orientation type, must be one of "{'vertical', 'horizontal'}. If list is supplied it must be the same length as the length of | 'vertical' |
color | str | tuple | list | If string can be any color name recognized by vispy or hex value if starting with | None |
z_index | int | list | Specifier of z order priority. Shapes with higher z order are displayed on top of others. If a list is supplied it must be the same length as the length of | None |
move(index: int, new_data: tuple[float, float], orientation=None, finished: bool = False)
Move region to new location
move_to_back() -> None
Moves selected objects to be displayed behind all others.
move_to_front() -> None
Moves selected objects to be displayed in front of all others.
remove_selected() -> None
Remove any selected shapes.
Scatter
Bases: Points, LayerMixin
Scatter layer based on napari Points layer.
Set mode to "add" to add points by clicking, or to "select" to select and drag points. Drag boxes select fixed-size markers by their centers. Use remove_selected to delete selected points.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | array(N, 2) | Coordinates for N points in 2 dimensions. Data is expected as [y, x] | None |
features | dict[str, array - like] or DataFrame | Features table where each row corresponds to a point and each column is a feature. | None |
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. | None |
property_choices | dict {str: array (N,)} | possible values for each property. | None |
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. | None |
symbol | str | Symbol 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. | 'o' |
size | (float, array) | Size of the point marker in screen pixels (or data units when | 10 |
border_width | (float, array) | Width of the symbol edge in pixels. | 0.05 |
border_width_is_relative | bool | If enabled, border_width is interpreted as a fraction of the point size. | True |
border_color | (str, array - like, dict) | Color of the point marker border. Numeric color values should be RGB(A). | 'dimgray' |
border_color_cycle | (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. | None |
border_colormap | (str, Colormap) | Colormap to set border_color if a continuous attribute is used to set face_color. | 'viridis' |
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()) | None |
face_color | (str, array - like, dict) | Color of the point marker body. Numeric color values should be RGB(A). | 'white' |
face_color_cycle | (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. | None |
face_colormap | (str, Colormap) | Colormap to set face_color if a continuous attribute is used to set face_color. | 'viridis' |
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()) | None |
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. | None |
name | str | Name of the layer. | None |
metadata | dict | Layer metadata. | None |
scale | tuple of float | Scale factors for the layer. | None |
translate | tuple of float | Translation values for the layer. | None |
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. | None |
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. | None |
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 | None |
opacity | float | Opacity of the layer visual, between 0.0 and 1.0. | 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'}. | 'translucent' |
visible | bool | Whether the layer visual is currently being displayed. | True |
cache | bool | Whether slices of out-of-core datasets should be cached upon retrieval. Currently, this only applies to dask arrays. | True |
shading | (str, Shading) | Render lighting and shading on points. Options are:
| 'none' |
antialiasing | Amount of antialiasing in canvas pixels. | 1 | |
canvas_size_limits | tuple of float | Lower and upper limits for the size of points in canvas pixels. | (2, 10000) |
shown | 1-D array of bool | Whether to show each point. | True |
scaling | bool | Whether to scale the points with the zoom level. When False (default), marker sizes are in screen pixels. | False |
data: np.ndarray property writable
(N, D) array: coordinates for N points in D dimensions.
scaling: bool property writable
Scaling of the markers
x: np.ndarray property writable
Return x-axis array.
y: np.ndarray property writable
Return y-axis array.
Text
Bases: BaseLayer
Display text labels at xy plot coordinates.
Set mode to "move" to drag individual labels in the canvas.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | (array - like, shape(N, 2)) | Label positions in | None |
text | str or sequence of str | Text to display. A string is broadcast to every coordinate. | None |
size | float | Layer-wide font size in screen points. None uses the application setting. | None |
color | color-like or sequence of color-like | Text color, either shared or one color per label. | 'white' |
alignment | str | Layer-wide horizontal anchor: | 'center' |
vertical_alignment | str | Layer-wide vertical anchor: | 'center' |
rotation | float or array-like of float | Clockwise rotation in degrees, either shared or one value per label. | 0 |
offset | (array - like, shape(2) or (N, 2)) | Offset from each xy coordinate in plot data units. | (0, 0) |
pixel_offset | (array - like, shape(2) or (N, 2)) | Extra offset in screen pixels (x to the right, y up), added after | (0, 0) |
font_face | str | Font family shared by the layer. By default the application font is used. | None |
bold | bool | Whether to render the layer text in bold. | False |
italic | bool | Whether to render the layer text in italics. | False |
alignment: str property writable
Return the layer-wide horizontal alignment.
bold: bool property writable
Return whether text is bold.
color: np.ndarray property writable
Return text colors as an (N, 4) RGBA array.
data: np.ndarray property writable
Return label positions in [x, y] order.
effective_size: float property
Return the explicit font size or the application default.
font_face: str | None property writable
Return the layer-wide font family.
italic: bool property writable
Return whether text is italic.
offset: np.ndarray property writable
Return xy offsets in plot data units.
pixel_offset: np.ndarray property writable
Return xy offsets in screen pixels (x to the right, y up).
rotation: np.ndarray property writable
Return clockwise rotations in degrees.
size: float | None property writable
Return the layer-wide font size in screen points.
text: np.ndarray property writable
Return one text label per coordinate.
vertical_alignment: str property writable
Return the layer-wide vertical alignment.
x: np.ndarray property writable
Return x coordinates.
y: np.ndarray property writable
Return y coordinates.
Statistical plots
barplot(viewer: ViewerModel, data: ty.Any = None, *, x: ty.Any = None, y: ty.Any = None, hue: ty.Any = None, order: list | None = None, hue_order: list | None = None, orient: str | None = None, palette: ty.Any = None, color: ty.Any = None, estimator: ty.Any = 'mean', errorbar: ty.Any = ('ci', 95), n_boot: int = 1000, seed: ty.Any = None, width: float = 0.8, dodge: bool = True, err_color: ty.Any = 'lightgray', err_width: float = 1.5, capsize: float = 0.0, linecolor: ty.Any = 'transparent', linewidth: float = 1.0, legend: bool = True, name: str = 'barplot', group: str | None = None) -> list[Layer]
Draw (grouped) bars of a point estimate per category with error bars.
Parameters are as for :func:boxplot, plus:
estimator : str or callable Statistic per group ("mean", "median", np.sum, ...). errorbar : str, (str, float), callable or None "ci", "pi", "se", "sd" with optional level, as in seaborn. None hides error bars. n_boot, seed Bootstrap settings for "ci". err_color, err_width : color, float Error bar style (width in screen pixels). capsize : float Error bar cap length in screen pixels.
Returns:
| Type | Description |
|---|---|
list of Layer | Created layers in drawing order. |
boxenplot(viewer: ViewerModel, data: ty.Any = None, *, x: ty.Any = None, y: ty.Any = None, hue: ty.Any = None, order: list | None = None, hue_order: list | None = None, orient: str | None = None, palette: ty.Any = None, color: ty.Any = None, width: float = 0.8, dodge: bool = True, saturation: float = 1.0, k_depth: str | int = 'tukey', width_method: str = 'exponential', outlier_prop: float = 0.007, trust_alpha: float = 0.05, linecolor: ty.Any = 'lightgray', linewidth: float = 1.0, showfliers: bool = True, fliersize: float = 5, legend: bool = True, name: str = 'boxenplot', group: str | None = None) -> list[Layer]
Draw letter-value (boxen) plots: nested boxes for successively finer quantiles.
Parameters are as for :func:boxplot, plus k_depth ("tukey", "proportion", "trustworthy", "full" or an int), width_method ("exponential", "linear" or "area"), outlier_prop and trust_alpha which follow seaborn's boxenplot.
Returns:
| Type | Description |
|---|---|
list of Layer | Created layers in drawing order. |
boxplot(viewer: ViewerModel, data: ty.Any = None, *, x: ty.Any = None, y: ty.Any = None, hue: ty.Any = None, order: list | None = None, hue_order: list | None = None, orient: str | None = None, palette: ty.Any = None, color: ty.Any = None, width: float = 0.8, dodge: bool = True, saturation: float = 1.0, whis: float | tuple[float, float] = 1.5, linecolor: ty.Any = 'lightgray', linewidth: float = 1.5, showfliers: bool = True, fliersize: float = 5, legend: bool = True, name: str = 'boxplot', group: str | None = None) -> list[Layer]
Draw box-and-whisker plots of values grouped by category (and hue).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
viewer | ViewerModel | Viewer to draw on. | required |
data | DataFrame, dict, array or sequence of arrays | Long-form table (with | None |
x | str or array - like | Column names or vectors. The non-numeric of | None |
y | str or array - like | Column names or vectors. The non-numeric of | None |
hue | str or array - like | Column names or vectors. The non-numeric of | None |
order | list | Order of category and hue levels. | None |
hue_order | list | Order of category and hue levels. | None |
orient | ('v', 'h') | Orientation; inferred from the data types when omitted. | "v" |
palette | (str, list or dict) | seaborn palette for hue levels (or categories when no hue is given). | None |
color | color | Single color for all boxes when no palette/hue is used. | None |
width | float | Width of each category slot in data units. | 0.8 |
dodge | bool | Place hue levels side by side instead of on top of each other. | True |
saturation | float | Fraction of the original color saturation to keep (seaborn uses 0.75 by default). | 1.0 |
whis | float or (float, float) | Whisker reach as a multiple of the IQR, or percentile bounds. | 1.5 |
linecolor | (color, float) | Style of whiskers, caps and medians (width in screen pixels). | 'lightgray' |
linewidth | (color, float) | Style of whiskers, caps and medians (width in screen pixels). | 'lightgray' |
showfliers | bool | Whether to draw outliers. | True |
fliersize | float | Outlier marker size in screen pixels. | 5 |
legend | bool | Show a legend for hue levels. | True |
name | str | Prefix for created layer names. | 'boxplot' |
group | str | Shared layer group ID. A fresh ID is generated when omitted or None. | None |
Returns:
| Type | Description |
|---|---|
list of Layer | Created layers in drawing order. |
catplot(viewer: ViewerModel, data: Any = None, *, x: Any = None, y: Any = None, hue: Any = None, kind: str = 'strip', facet_kws: dict[str, Any] | None = None, row: Any = None, col: Any = None, col_wrap: int | None = None, row_order: Sequence[Any] | None = None, col_order: Sequence[Any] | None = None, **kwargs: Any) -> FacetGrid
Draw a categorical plot per subset with consistent category and hue levels.
clustermap(viewer: ViewerModel, data: ty.Any, *, method: str = 'average', metric: str = 'euclidean', z_score: int | None = None, standard_scale: int | None = None, row_cluster: bool = True, col_cluster: bool = True, row_linkage: np.ndarray | None = None, col_linkage: np.ndarray | None = None, dendrogram_ratio: float = 0.2, tree_color: ty.Any = 'lightgray', tree_width: float = 1.0, name: str = 'clustermap', group: str | None = None, **heatmap_kws: ty.Any) -> list[Layer]
Draw a hierarchically clustered heatmap with row/column dendrograms in the canvas margins.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
viewer | ViewerModel | Viewer to draw on. | required |
data | 2D array-like or DataFrame | Matrix to cluster and draw. | required |
method | str | Linkage method and distance metric (scipy). | 'average' |
metric | str | Linkage method and distance metric (scipy). | 'average' |
z_score | (0, 1) | Standardize (z-score) or min-max scale rows (0) or columns (1) before clustering. | 0 |
standard_scale | (0, 1) | Standardize (z-score) or min-max scale rows (0) or columns (1) before clustering. | 0 |
row_cluster | bool | Whether to cluster and draw a dendrogram for rows / columns. | True |
col_cluster | bool | Whether to cluster and draw a dendrogram for rows / columns. | True |
row_linkage | array | Precomputed linkage matrices. | None |
col_linkage | array | Precomputed linkage matrices. | None |
dendrogram_ratio | float | Dendrogram depth as a fraction of the heatmap height (columns) or width (rows). | 0.2 |
tree_color | Any | Dendrogram line style (width in screen pixels). | 'lightgray' |
tree_width | Any | Dendrogram line style (width in screen pixels). | 'lightgray' |
name | str | Prefix for created layer names. | 'clustermap' |
group | str | Shared layer group ID for the heatmap and dendrograms. A fresh ID is generated when omitted or None. | None |
**heatmap_kws | Any | Passed to :func: | {} |
Returns:
| Type | Description |
|---|---|
list of Layer | Created layers in drawing order. |
countplot(viewer: ViewerModel, data: ty.Any = None, *, x: ty.Any = None, y: ty.Any = None, hue: ty.Any = None, stat: str = 'count', name: str = 'countplot', **kwargs: ty.Any) -> list[Layer]
Count rows per category, optionally split by hue or normalized over all rows.
displot(viewer: ViewerModel, data: Any = None, *, x: Any = None, y: Any = None, hue: Any = None, kind: str = 'hist', facet_kws: dict[str, Any] | None = None, row: Any = None, col: Any = None, col_wrap: int | None = None, row_order: Sequence[Any] | None = None, col_order: Sequence[Any] | None = None, **kwargs: Any) -> FacetGrid
Draw histograms, KDEs, or ECDFs across data facets.
distplot(viewer: ViewerModel, a: ty.Any = None, *, data: ty.Any = None, x: ty.Any = None, y: ty.Any = None, hue: ty.Any = None, hue_order: list | None = None, palette: ty.Any = None, color: ty.Any = None, bins: ty.Any = 'auto', hist: bool = True, kde: bool = True, rug: bool = False, rug_height: float = 0.025, hist_kws: dict | None = None, kde_kws: dict | None = None, legend: bool = True, name: str = 'distplot', group: str | None = None) -> list[Layer]
Draw a density-normalized histogram with a KDE curve and optional rug (seaborn's classic distplot).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
viewer | ViewerModel | Viewer to draw on. | required |
a | array - like | Observations (shortcut for | None |
data | Any | As in :func: | None |
x | Any | As in :func: | None |
y | Any | As in :func: | None |
hue | Any | As in :func: | None |
hue_order | Any | As in :func: | None |
palette | Any | As in :func: | None |
color | Any | As in :func: | None |
bins | (str, int or array) | Histogram bins. | 'auto' |
hist | bool | Which components to draw. | True |
kde | bool | Which components to draw. | True |
rug | bool | Which components to draw. | True |
rug_height | float | Rug tick length as a fraction of the highest density. | 0.025 |
hist_kws | dict | Extra :func: | None |
kde_kws | dict | Extra :func: | None |
legend | bool | Show a legend for hue levels. | True |
name | str | Prefix for created layer names. | 'distplot' |
group | str | Shared layer group ID for all components. A fresh ID is generated when omitted or None. | None |
Returns:
| Type | Description |
|---|---|
list of Layer | Created layers in drawing order. |
ecdfplot(viewer: ViewerModel, data: ty.Any = None, *, x: ty.Any = None, y: ty.Any = None, hue: ty.Any = None, hue_order: list | None = None, stat: str = 'proportion', complementary: bool = False, palette: ty.Any = None, color: ty.Any = None, linewidth: float = 2, legend: bool = True, name: str = 'ecdfplot', group: str | None = None) -> list[Layer]
Draw the empirical cumulative distribution as a step curve for each group.
heatmap(viewer: ViewerModel, data: ty.Any, *, vmin: float | None = None, vmax: float | None = None, cmap: ty.Any = None, center: float | None = None, robust: bool = False, annot: ty.Any = None, fmt: str = '.2g', annot_size: float | None = None, annot_color: ty.Any = None, mask: ty.Any = None, xticklabels: ty.Any = True, yticklabels: ty.Any = True, cbar: bool = False, name: str = 'heatmap', group: str | None = None) -> list[Layer]
Draw a matrix as a color-encoded image, optionally annotating each cell with its value.
Rows are drawn top to bottom like seaborn; DataFrame index/columns label the axes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
viewer | ViewerModel | Viewer to draw on. | required |
data | 2D array-like or DataFrame | Matrix to draw. | required |
vmin | float | Colormap limits (data range, or 2nd/98th percentiles with | None |
vmax | float | Colormap limits (data range, or 2nd/98th percentiles with | None |
cmap | str, list or matplotlib colormap | Colormap (seaborn's | None |
center | float | Value at the center of a diverging colormap. | None |
robust | bool | Use robust quantiles for the default limits. | False |
annot | bool or array - like | Annotate cells with the data (True) or with values of an array of the same shape. | None |
fmt | str | Format spec for annotations. | '.2g' |
annot_size | float | Annotation font size in screen points; by default derived from the cell size on the current canvas. | None |
annot_color | color | Annotation color; by default chosen per cell for contrast. | None |
mask | bool array-like | Cells where True are not drawn or annotated. | None |
xticklabels | (bool, int, list or 'auto') | Tick labels as in seaborn (int labels every n-th cell). | True |
yticklabels | (bool, int, list or 'auto') | Tick labels as in seaborn (int labels every n-th cell). | True |
cbar | bool | Show the viewer colorbar next to the plot, following the heatmap's colormap and limits. | False |
name | str | Prefix for created layer names. | 'heatmap' |
group | str | Shared layer group ID. A fresh ID is generated when omitted or None. | None |
Returns:
| Type | Description |
|---|---|
list of Layer | Created layers in drawing order. |
histplot(viewer: ViewerModel, data: ty.Any = None, *, x: ty.Any = None, y: ty.Any = None, hue: ty.Any = None, hue_order: list | None = None, palette: ty.Any = None, color: ty.Any = None, stat: str = 'count', bins: ty.Any = 'auto', binwidth: float | None = None, binrange: tuple[float, float] | None = None, discrete: bool = False, cumulative: bool = False, common_bins: bool = True, common_norm: bool = True, multiple: str = 'layer', element: str = 'bars', fill: bool = True, shrink: float = 1.0, kde: bool = False, kde_kws: dict | None = None, alpha: float | None = None, linecolor: ty.Any = 'transparent', linewidth: float = 1.0, legend: bool = True, name: str = 'histplot', group: str | None = None) -> list[Layer]
Draw univariate or bivariate histograms, optionally split by hue.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
viewer | ViewerModel | Viewer to draw on. | required |
data | Any | As in :func: | None |
x | Any | As in :func: | None |
y | Any | As in :func: | None |
hue | Any | As in :func: | None |
hue_order | Any | As in :func: | None |
palette | Any | As in :func: | None |
color | Any | As in :func: | None |
stat | ('count', 'frequency', 'density', 'probability', 'proportion', 'percent') | Statistic computed in each bin. | "count" |
bins | Any | Bin definition, as in seaborn. | 'auto' |
binwidth | Any | Bin definition, as in seaborn. | 'auto' |
binrange | Any | Bin definition, as in seaborn. | 'auto' |
discrete | Any | Bin definition, as in seaborn. | 'auto' |
cumulative | bool | Accumulate bin heights. | False |
common_bins | bool | Use the same bins for every hue level (required for | True |
common_norm | bool | Normalize normalized stats over all levels rather than within each level. | True |
multiple | ('layer', 'stack', 'dodge', 'fill') | Arrangement of hue levels. | "layer" |
element | ('bars', 'step', 'poly') | Geometry of a univariate histogram. | "bars" |
fill | bool | Fill the histogram geometry. | True |
shrink | float | Fraction of the bin width each bar occupies. | 1.0 |
kde | bool | Overlay a kernel density estimate scaled to the histogram. | False |
kde_kws | dict | Extra :func: | None |
alpha | float | Bar opacity (defaults to 0.5 when layered hue levels overlap, otherwise 0.75). | None |
linecolor | Any | Bar outline style. | 'transparent' |
linewidth | Any | Bar outline style. | 'transparent' |
legend | bool | Show a legend for hue levels. | True |
name | str | Prefix for created layer names. | 'histplot' |
group | str | Shared layer group ID. A fresh ID is generated when omitted or None. | None |
Returns:
| Type | Description |
|---|---|
list of Layer | Created layers in drawing order. |
jointplot(viewer: ViewerModel, data: Any = None, *, x: Any, y: Any, hue: Any = None, kind: str = 'scatter', joint_kws: dict[str, Any] | None = None, marginal_kws: dict[str, Any] | None = None, ratio: float = 5) -> JointGrid
Draw a bivariate plot and its two marginal distributions.
kdeplot(viewer: ViewerModel, data: ty.Any = None, *, x: ty.Any = None, y: ty.Any = None, hue: ty.Any = None, hue_order: list | None = None, palette: ty.Any = None, color: ty.Any = None, fill: bool = False, multiple: str = 'layer', common_norm: bool = True, cumulative: bool = False, bw_method: ty.Any = 'scott', bw_adjust: float = 1.0, gridsize: int = 200, cut: float = 3, clip: tuple[float | None, float | None] | None = None, linewidth: float = 2.0, alpha: float = 0.25, legend: bool = True, name: str = 'kdeplot', group: str | None = None) -> list[Layer]
Draw univariate curves or a bivariate density when both coordinates are supplied.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
viewer | ViewerModel | Viewer to draw on. | required |
data | (DataFrame, dict or array) | Long-form table (with | None |
x | str or array - like | Observations along x (density on y) or along y (density on x). | None |
y | str or array - like | Observations along x (density on y) or along y (density on x). | None |
hue | str or array - like | Grouping variable; one curve per level. | None |
hue_order | list | None | Level order and colors, as in seaborn. | None |
palette | list | None | Level order and colors, as in seaborn. | None |
color | list | None | Level order and colors, as in seaborn. | None |
fill | bool | Fill the area under each curve. | False |
multiple | ('layer', 'stack', 'fill') | Overlay, stack, or normalize univariate curves at each coordinate. | "layer" |
common_norm | bool | Scale each curve by its share of observations so all curves integrate to 1 together. | True |
cumulative | bool | Draw the cumulative distribution instead of the density. | False |
bw_method | Any | KDE parameters, as in seaborn. | 'scott' |
bw_adjust | Any | KDE parameters, as in seaborn. | 'scott' |
gridsize | Any | KDE parameters, as in seaborn. | 'scott' |
cut | Any | KDE parameters, as in seaborn. | 'scott' |
clip | Any | KDE parameters, as in seaborn. | 'scott' |
linewidth | float | Curve width in screen pixels. | 2.0 |
alpha | float | Opacity of the fill. | 0.25 |
legend | bool | Show a legend for hue levels. | True |
name | str | Prefix for created layer names. | 'kdeplot' |
group | str | Shared layer group ID. A fresh ID is generated when omitted or None. | None |
Returns:
| Type | Description |
|---|---|
list of Layer | Created layers in drawing order. |
lineplot(viewer: ViewerModel, data: ty.Any = None, *, x: ty.Any = None, y: ty.Any = None, hue: ty.Any = None, size: ty.Any = None, style: ty.Any = None, hue_order: list | None = None, size_order: list | None = None, style_order: list | None = None, sizes: tuple[float, float] = (1, 4), dashes: ty.Any = True, markers: ty.Any = None, palette: ty.Any = None, color: ty.Any = None, estimator: ty.Any = 'mean', errorbar: ty.Any = ('ci', 95), n_boot: int = 1000, seed: ty.Any = None, sort: bool = True, err_style: str = 'band', linewidth: float = 2.0, err_alpha: float = 0.2, legend: bool = True, name: str = 'lineplot', group: str | None = None) -> list[Layer]
Draw lines through y per x, aggregating repeated x values with an error band.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
viewer | ViewerModel | Viewer to draw on. | required |
data | Any | As in :func: | None |
x | Any | As in :func: | None |
y | Any | As in :func: | None |
hue | Any | As in :func: | None |
hue_order | Any | As in :func: | None |
palette | Any | As in :func: | None |
color | Any | As in :func: | None |
size | Any | Map a variable to a line width within the specified width range. | None |
sizes | Any | Map a variable to a line width within the specified width range. | None |
size_order | Any | Map a variable to a line width within the specified width range. | None |
style | Any | Map a variable to dash patterns and optional markers. Pass a mapping of style levels to patterns or symbols for explicit styling. | None |
dashes | Any | Map a variable to dash patterns and optional markers. Pass a mapping of style levels to patterns or symbols for explicit styling. | None |
markers | Any | Map a variable to dash patterns and optional markers. Pass a mapping of style levels to patterns or symbols for explicit styling. | None |
style_order | Any | Map a variable to dash patterns and optional markers. Pass a mapping of style levels to patterns or symbols for explicit styling. | None |
estimator | (str, callable or None) | Aggregate of | 'mean' |
errorbar | (str, (str, float), callable or None) | Interval around the estimate ( | ('ci', 95) |
n_boot | int | Bootstrap settings for | 1000 |
seed | int | Bootstrap settings for | 1000 |
sort | bool | Sort observations by | True |
err_style | ('band', 'bars') | Draw the interval as a filled band or as error bars. | "band" |
linewidth | float | Line width in screen pixels. | 2.0 |
err_alpha | float | Opacity of the error band. | 0.2 |
legend | bool | Show a legend for hue levels. | True |
name | str | Prefix for created layer names. | 'lineplot' |
group | str | Shared layer group ID. A fresh ID is generated when omitted or None. | None |
Returns:
| Type | Description |
|---|---|
list of Layer | Created layers in drawing order. |
lmplot(viewer: ViewerModel, data: Any = None, *, x: Any = None, y: Any = None, hue: Any = None, hue_order: Sequence[Any] | None = None, palette: Any = None, legend: bool = True, row: Any = None, col: Any = None, col_wrap: int | None = None, row_order: Sequence[Any] | None = None, col_order: Sequence[Any] | None = None, facet_kws: dict[str, Any] | None = None, **kwargs: Any) -> FacetGrid
Fit and display a regression in each subset of the data.
pairplot(viewer: ViewerModel, data: Any, *, vars: Sequence[str] | None = None, x_vars: Sequence[str] | None = None, y_vars: Sequence[str] | None = None, hue: Any = None, kind: str = 'scatter', diag_kind: str = 'hist', corner: bool = False, plot_kws: dict[str, Any] | None = None, diag_kws: dict[str, Any] | None = None) -> PairGrid
Draw pairwise plots for numeric columns and distributions for matching columns.
pointplot(viewer: ViewerModel, data: ty.Any = None, *, x: ty.Any = None, y: ty.Any = None, hue: ty.Any = None, order: list | None = None, hue_order: list | None = None, orient: str | None = None, palette: ty.Any = None, color: ty.Any = None, estimator: ty.Any = 'mean', errorbar: ty.Any = ('ci', 95), n_boot: int = 1000, seed: ty.Any = None, dodge: bool = False, width: float = 0.4, markers: str = 'disc', size: float = 7, linewidth: float = 2, capsize: float = 0, legend: bool = True, name: str = 'pointplot', group: str | None = None) -> list[Layer]
Draw category estimates as points joined by lines, with optional error intervals.
regplot(viewer: ViewerModel, data: ty.Any = None, *, x: ty.Any = None, y: ty.Any = None, order: int = 1, ci: float | None = 95, n_boot: int = 1000, seed: ty.Any = None, logx: bool = False, scatter: bool = True, fit_reg: bool = True, color: ty.Any = None, scatter_kws: dict[str, ty.Any] | None = None, line_kws: dict[str, ty.Any] | None = None, name: str = 'regplot', group: str | None = None) -> list[Layer]
Plot observations and a linear, polynomial, or logarithmic regression with a bootstrap band.
relplot(viewer: ViewerModel, data: ty.Any = None, *, x: ty.Any = None, y: ty.Any = None, hue: ty.Any = None, size: ty.Any = None, style: ty.Any = None, kind: str = 'scatter', **kwargs: ty.Any) -> list[Layer]
Draw a relational plot on one canvas: kind="scatter" (:func:scatterplot) or "line" (:func:lineplot).
Row/column faceting is not supported. Extra keyword arguments go to the selected plot function.
Returns:
| Type | Description |
|---|---|
list of Layer | Created layers in drawing order. |
rugplot(viewer: ViewerModel, data: ty.Any = None, *, x: ty.Any = None, y: ty.Any = None, hue: ty.Any = None, height: float = 0.025, expand_margins: bool = True, palette: ty.Any = None, hue_order: list | None = None, hue_norm: ty.Any = None, color: ty.Any = None, linewidth: float = 1.0, alpha: float | None = None, legend: bool = True, name: str = 'rugplot', group: str | None = None) -> list[Layer]
Draw one tick per observation along the bottom (x) or left (y) of the plot.
Pass either or both of x and y as columns or vectors. As in seaborn, hue colors observations using palette, hue_order and hue_norm. height is a fraction of the perpendicular axis span at call time. Positive ticks point into the plot and negative ticks point out. expand_margins adds room between the ticks and existing data. linewidth is in screen pixels.
Returns one MultiLine layer per plotted axis. Ticks use data coordinates after placement. Use group to share a layer group ID. The default generates a fresh ID.
scatterplot(viewer: ViewerModel, data: ty.Any = None, *, x: ty.Any = None, y: ty.Any = None, hue: ty.Any = None, size: ty.Any = None, style: ty.Any = None, hue_order: list | None = None, hue_norm: tuple[float, float] | None = None, size_order: list | None = None, style_order: list | None = None, palette: ty.Any = None, color: ty.Any = None, sizes: tuple[float, float] = (4, 14), markers: ty.Any = True, marker_size: float = 7, linecolor: ty.Any = 'transparent', opacity: float = 1.0, legend: bool = True, name: str = 'scatterplot', group: str | None = None) -> list[Layer]
Draw a scatter plot whose color, size and marker can encode extra variables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
viewer | ViewerModel | Viewer to draw on. | required |
data | DataFrame or dict | Long-form table whose columns are named by | None |
x | str or array - like | Coordinates. | None |
y | str or array - like | Coordinates. | None |
hue | str or array - like | Color grouping; numeric values map onto a colormap ( | None |
size | str or array - like | Marker size grouping, mapped into the | None |
style | str or array - like | Marker symbol grouping, using | None |
hue_order | list | None | Level orders and the numeric hue range. | None |
hue_norm | list | None | Level orders and the numeric hue range. | None |
size_order | list | None | Level orders and the numeric hue range. | None |
style_order | list | None | Level orders and the numeric hue range. | None |
palette | Any | Colors, as in seaborn. | None |
color | Any | Colors, as in seaborn. | None |
marker_size | float | Marker size in screen pixels when | 7 |
linecolor | color | Marker outline color. | 'transparent' |
opacity | float | Layer opacity. | 1.0 |
legend | bool | Show a legend for hue and style levels. | True |
name | str | Layer name. | 'scatterplot' |
group | str | Layer group ID used to place related layers in the same plot cell. | None |
Returns:
| Type | Description |
|---|---|
list of Layer | Created layers. |
stripplot(viewer: ViewerModel, data: ty.Any = None, *, x: ty.Any = None, y: ty.Any = None, hue: ty.Any = None, order: list | None = None, hue_order: list | None = None, orient: str | None = None, palette: ty.Any = None, color: ty.Any = None, jitter: float | bool = True, dodge: bool = False, width: float = 0.8, size: float = 6, linecolor: ty.Any = 'transparent', linewidth: float = 0.0, seed: ty.Any = None, legend: bool = True, name: str = 'stripplot', group: str | None = None) -> list[Layer]
Draw every observation as a point, jittered along the categorical axis.
Parameters are as for :func:boxplot, plus jitter (True for the default amount, or the half-width of the jitter in data units), size (marker size in screen pixels), linewidth (marker border width in screen pixels) and seed for reproducible jitter. Use group to share a layer group ID. The default generates a fresh ID.
Returns:
| Type | Description |
|---|---|
list of Layer | Created layers in drawing order. |
swarmplot(viewer: ViewerModel, data: ty.Any = None, *, x: ty.Any = None, y: ty.Any = None, hue: ty.Any = None, order: list | None = None, hue_order: list | None = None, orient: str | None = None, palette: ty.Any = None, color: ty.Any = None, dodge: bool = False, width: float = 0.8, size: float = 6, linecolor: ty.Any = 'transparent', linewidth: float = 0.0, warn_thresh: float = 0.05, legend: bool = True, name: str = 'swarmplot', group: str | None = None) -> list[Layer]
Draw a beeswarm, spreading points along the categorical axis to avoid overlap.
Point positions are computed for the canvas size at call time; zooming changes the apparent spacing. With dodge=False, hue levels share a swarm in each category. warn_thresh sets the fraction of points that can reach the gutters before seaborn warns. Set it to 1 to suppress crowding warnings. Other parameters are shared with :func:stripplot.
Returns:
| Type | Description |
|---|---|
list of Layer | Created layers in drawing order. |
violinplot(viewer: ViewerModel, data: ty.Any = None, *, x: ty.Any = None, y: ty.Any = None, hue: ty.Any = None, order: list | None = None, hue_order: list | None = None, orient: str | None = None, palette: ty.Any = None, color: ty.Any = None, width: float = 0.8, dodge: bool = True, saturation: float = 1.0, split: bool = False, inner: str | None = 'box', density_norm: str = 'area', common_norm: bool = False, bw_method: ty.Any = 'scott', bw_adjust: float = 1.0, cut: float = 2, gridsize: int = 100, linecolor: ty.Any = 'lightgray', linewidth: float = 1.0, legend: bool = True, name: str = 'violinplot', group: str | None = None) -> list[Layer]
Draw violin plots: mirrored kernel density estimates of values per category (and hue).
Parameters are as for :func:boxplot, plus:
split : bool With exactly two hue levels, draw one half-violin per level instead of dodging. inner : {"box", "quart", "stick", "point", None} Representation of the observations inside each violin. density_norm : {"area", "count", "width"} Scale violins to equal area, to their number of observations, or to equal width. common_norm : bool Normalize the density across all violins rather than within each category. group : str, optional Shared layer group ID. A fresh ID is generated when omitted or None. bw_method, bw_adjust, cut, gridsize KDE parameters, as in seaborn.
Returns:
| Type | Description |
|---|---|
list of Layer | Created layers in drawing order. |