Visuals

vispy.visuals

This module provides a library of Visual classes, which are drawable objects intended to encapsulate simple graphic objects such as lines, meshes, points, 2D shapes, images, text, etc.

These classes define only the OpenGL machinery and connot be used directly in a scenegraph. For scenegraph use, see the complementary Visual+Node classes defined in vispy.scene.

class vispy.visuals.ArrowVisual(pos=None, color=(0.5, 0.5, 0.5, 1), width=1, connect='strip', method='gl', antialias=False, arrows=None, arrow_type='stealth', arrow_size=None, arrow_color=(0.5, 0.5, 0.5, 1))[source]

Bases: vispy.visuals.line.line.LineVisual

Arrow visual

A special line visual which can also draw optional arrow heads at the specified vertices.

You add an arrow head by specifying two vertices v1 and v2 which represent the arrow body. This visual will draw an arrow head using v2 as center point, and the orientation of the arrow head is automatically determined by calculating the direction vector between v1 and v2.

Parameters:

pos : array

Array of shape (…, 2) or (…, 3) specifying vertex coordinates.

color : Color, tuple, or array

The color to use when drawing the line. If an array is given, it must be of shape (…, 4) and provide one rgba color per vertex. Can also be a colormap name, or appropriate Function.

width:

The width of the line in px. Line widths > 1px are only guaranteed to work when using ‘agg’ method.

connect : str or array

Determines which vertices are connected by lines.

  • “strip” causes the line to be drawn with each vertex connected to the next.
  • “segments” causes each pair of vertices to draw an independent line segment
  • numpy arrays specify the exact set of segment pairs to connect.

method : str

Mode to use for drawing.

  • “agg” uses anti-grain geometry to draw nicely antialiased lines with proper joins and endcaps.
  • “gl” uses OpenGL’s built-in line rendering. This is much faster, but produces much lower-quality results and is not guaranteed to obey the requested line width or join/endcap styles.

antialias : bool

Enables or disables antialiasing. For method=’gl’, this specifies whether to use GL’s line smoothing, which may be unavailable or inconsistent on some platforms.

arrows : array

A (N, 4) or (N, 6) matrix where each row contains the (x, y) or the (x, y, z) coordinate of the first and second vertex of the arrow body. Remember that the second vertex is used as center point for the arrow head, and the first vertex is only used for determining the arrow head orientation.

arrow_type : string

Specify the arrow head type, the currently available arrow head types are:

  • stealth
  • curved
  • triangle_30
  • triangle_60
  • triangle_90
  • angle_30
  • angle_60
  • angle_90
  • inhibitor_round

arrow_size : float

Specify the arrow size

arrow_color : Color, tuple, or array

The arrow head color. If an array is given, it must be of shape (…, 4) and provide one rgba color per arrow head. Can also be a colormap name, or appropriate Function.

set_data(pos=None, color=None, width=None, connect=None, arrows=None)[source]

Set the data used for this visual

Parameters:

pos : array

Array of shape (…, 2) or (…, 3) specifying vertex coordinates.

color : Color, tuple, or array

The color to use when drawing the line. If an array is given, it must be of shape (…, 4) and provide one rgba color per vertex. Can also be a colormap name, or appropriate Function.

width:

The width of the line in px. Line widths > 1px are only guaranteed to work when using ‘agg’ method.

connect : str or array

Determines which vertices are connected by lines.

  • “strip” causes the line to be drawn with each vertex connected to the next.
  • “segments” causes each pair of vertices to draw an independent line segment
  • numpy arrays specify the exact set of segment pairs to connect.

arrows : array

A (N, 4) or (N, 6) matrix where each row contains the (x, y) or the (x, y, z) coordinate of the first and second vertex of the arrow body. Remember that the second vertex is used as center point for the arrow head, and the first vertex is only used for determining the arrow head orientation.

class vispy.visuals.AxisVisual(pos=None, domain=(0.0, 1.0), tick_direction=(-1.0, 0.0), scale_type='linear', axis_color=(1, 1, 1), tick_color=(0.7, 0.7, 0.7), text_color='w', minor_tick_length=5, major_tick_length=10, tick_width=2, tick_label_margin=5, tick_font_size=8, axis_width=3, axis_label=None, axis_label_margin=35, axis_font_size=10, font_size=None, anchors=None)[source]

Bases: vispy.visuals.visual.CompoundVisual

Axis visual

Parameters:

pos : array

Co-ordinates of start and end of the axis.

domain : tuple

The data values at the beginning and end of the axis, used for tick labels. i.e. (5, 10) means the axis starts at 5 and ends at 10. Default is (0, 1).

tick_direction : array

The tick direction to use (in document coordinates).

scale_type : str

The type of scale. For now only ‘linear’ is supported.

axis_color : tuple

RGBA values for the axis colour. Default is black.

tick_color : tuple

RGBA values for the tick colours. The colour for the major and minor ticks is currently fixed to be the same. Default is a dark grey.

text_color : Color

The color to use for drawing tick and axis labels

minor_tick_length : float

The length of minor ticks, in pixels

major_tick_length : float

The length of major ticks, in pixels

tick_width : float

Line width for the ticks

tick_label_margin : float

Margin between ticks and tick labels

tick_font_size : float

The font size to use for rendering tick labels.

axis_width : float

Line width for the axis

axis_label : str

Text to use for the axis label

axis_label_margin : float

Margin between ticks and axis labels

axis_font_size : float

The font size to use for rendering axis labels.

font_size : float

Font size for both the tick and axis labels. If this is set, tick_font_size and axis_font_size are ignored.

anchors : iterable

A 2-element iterable (tuple, list, etc.) giving the horizontal and vertical alignment of the tick labels. The first element should be one of ‘left’, ‘center’, or ‘right’, and the second element should be one of ‘bottom’, ‘middle’, or ‘top’. If this is not specified, it is determined automatically.

class vispy.visuals.BaseVisual(vshare=None)[source]

Bases: vispy.util.frozen.Frozen

Superclass for all visuals.

This class provides:

  • A TransformSystem.
  • Two events: update and bounds_change.
  • Minimal framework for creating views of the visual.
  • A data structure that is shared between all views of the visual.
  • Abstract draw, bounds, attach, and detach methods.
Parameters:

vshare : instance of VisualShare | None

The visual share.

Notes

When used in the scenegraph, all Visual classes are mixed with vispy.scene.Node in order to implement the methods, attributes and capabilities required for their usage within it.

This subclasses Frozen so that subclasses can easily freeze their properties.

attach(filt, view=None)[source]

Attach a Filter to this visual.

Each filter modifies the appearance or behavior of the visual.

Parameters:

filt : object

The filter to attach.

view : instance of VisualView | None

The view to use.

bounds(axis, view=None)[source]

Get the bounds of the Visual

Parameters:

axis : int

The axis.

view : instance of VisualView

The view to use.

detach(filt, view=None)[source]

Detach a filter.

Parameters:

filt : object

The filter to detach.

view : instance of VisualView | None

The view to use.

get_transform(map_from='visual', map_to='render')[source]

Return a transform mapping between any two coordinate systems.

Parameters:

map_from : str

The starting coordinate system to map from. Must be one of: visual, scene, document, canvas, framebuffer, or render.

map_to : str

The ending coordinate system to map to. Must be one of: visual, scene, document, canvas, framebuffer, or render.

update()[source]

Update the Visual

view()[source]

Return a new view of this visual.

class vispy.visuals.BoxVisual(width=1, height=1, depth=1, width_segments=1, height_segments=1, depth_segments=1, planes=None, vertex_colors=None, face_colors=None, color=(0.5, 0.5, 1, 1), edge_color=None, **kwargs)[source]

Bases: vispy.visuals.visual.CompoundVisual

Visual that displays a box.

Parameters:

width : float

Box width.

height : float

Box height.

depth : float

Box depth.

width_segments : int

Box segments count along the width.

height_segments : float

Box segments count along the height.

depth_segments : float

Box segments count along the depth.

planes: array_like

Any combination of {'-x', '+x', '-y', '+y', '-z', '+z'} Included planes in the box construction.

vertex_colors : ndarray

Same as for MeshVisual class. See create_plane for vertex ordering.

face_colors : ndarray

Same as for MeshVisual class. See create_plane for vertex ordering.

color : Color

The Color to use when drawing the cube faces.

edge_color : tuple or Color

The Color to use when drawing the cube edges. If None, then no cube edges are drawn.

border

The vispy.visuals.MeshVisual that used to draw the border.

mesh

The vispy.visuals.MeshVisual that used to fill in.

class vispy.visuals.ColorBarVisual(cmap, orientation, size, pos=[0, 0], label_str='', label_color='black', clim=(0.0, 1.0), border_width=1.0, border_color='black', **kwargs)[source]

Bases: vispy.visuals.visual.CompoundVisual

Visual subclass displaying a colorbar

Parameters:

cmap : str | vispy.color.ColorMap

Either the name of the ColorMap to be used from the standard set of names (refer to vispy.color.get_colormap), or a custom ColorMap object. The ColorMap is used to apply a gradient on the colorbar.

orientation : {‘left’, ‘right’, ‘top’, ‘bottom’}

The orientation of the colorbar, used for rendering. The orientation can be thought of as the position of the label relative to the color bar.

When the orientation is ‘left’ or ‘right’, the colorbar is vertically placed. When it is ‘top’ or ‘bottom’, the colorbar is horizontally placed.

  • ‘top’: the colorbar is horizontal. Color is applied from left to right. Minimum corresponds to left and maximum to right. Label is to the top of the colorbar
  • ‘bottom’: Same as top, except that label is to the bottom of the colorbar
  • ‘left’: the colorbar is vertical. Color is applied from bottom to top. Minimum corresponds to bottom and maximum to top. Label is to the left of the colorbar
  • ‘right’: Same as left, except that the label is placed to the right of the colorbar

size : (major_axis_length, minor_axis_length)

lengths with respect to the major and minor axes. The minor axis is the shorter axis, while the major axis is the longer axis with respect to the orientation

For orientations ‘top’ and ‘bottom’, the major axis is along the length.

For orientations ‘left’ and ‘right’, the major axis is along the breadth

pos : tuple (x, y)

Position where the colorbar is to be placed with respect to the center of the colorbar

label_str : str

The label that is to be drawn with the colorbar that provides information about the colorbar.

label_color : str | vispy.color.Color

The color of the labels. This can either be a str as the color’s name or an actual instace of a vipy.color.Color

clim : tuple (min, max)

the minimum and maximum values of the data that is given to the colorbar. This is used to draw the scale on the side of the colorbar.

border_width : float (in px)

The width of the border the colormap should have. This measurement is given in pixels

border_color : str | vispy.color.Color

The color of the border of the colormap. This can either be a str as the color’s name or an actual instace of a vipy.color.Color

border_color

The color of the border around the ColorBar in pixels

border_width

The width of the border around the ColorBar in pixels

clim

The data limits of the Colorbar

Returns:clim: tuple(min, max)
cmap

The colormap of the Colorbar

label

The vispy.visuals.TextVisual associated with the label

orientation

The orientation of the ColorBar

pos

The position of the text anchor in the local coordinate frame

size

The size of the ColorBar

Returns:

size: (major_axis_length, minor_axis_length)

major and minor axis are defined by the orientation of the ColorBar

ticks

The vispy.visuals.TextVisual associated with the ticks

Returns:

ticks: [vispy.visual.TextVisual]

The array is of length 2

class vispy.visuals.CompoundVisual(subvisuals)[source]

Bases: vispy.visuals.visual.BaseVisual

Visual consisting entirely of sub-visuals.

To the user, a compound visual behaves exactly like a normal visual–it has a transform system, draw() and bounds() methods, etc. Internally, the compound visual automatically manages proxying these transforms and methods to its sub-visuals.

Parameters:

subvisuals : list of BaseVisual instances

The list of visuals to be combined in this compound visual.

add_subvisual(visual)[source]

Add a subvisual

Parameters:

visual : instance of Visual

The visual to add.

attach(filt, view=None)[source]

Attach a Filter to this visual

Each filter modifies the appearance or behavior of the visual.

Parameters:

filt : object

The filter to attach.

view : instance of VisualView | None

The view to use.

detach(filt, view=None)[source]

Detach a filter.

Parameters:

filt : object

The filter to detach.

view : instance of VisualView | None

The view to use.

draw()[source]

Draw the visual

remove_subvisual(visual)[source]

Remove a subvisual

Parameters:

visual : instance of Visual

The visual to remove.

set_gl_state(preset=None, **kwargs)[source]

Define the set of GL state parameters to use when drawing

Parameters:

preset : str

Preset to use.

**kwargs : dict

Keyword arguments to gloo.set_state.

update_gl_state(*args, **kwargs)[source]

Modify the set of GL state parameters to use when drawing

Parameters:

*args : tuple

Arguments.

**kwargs : dict

Keyword argments.

class vispy.visuals.CubeVisual(size=1.0, vertex_colors=None, face_colors=None, color=(0.5, 0.5, 1, 1), edge_color=None, **kwargs)[source]

Bases: vispy.visuals.visual.CompoundVisual

Visual that displays a cube or cuboid

Parameters:

size : float or tuple

The size of the cuboid. A float gives a cube, whereas tuples may specify the size of each axis (x, y, z) independently.

vertex_colors : ndarray

Same as for MeshVisual class. See create_cube for vertex ordering.

face_colors : ndarray

Same as for MeshVisual class. See create_cube for vertex ordering.

color : Color

The Color to use when drawing the cube faces.

edge_color : tuple or Color

The Color to use when drawing the cube edges. If None, then no cube edges are drawn.

border

The vispy.visuals.MeshVisual that used to draw the border.

mesh

The vispy.visuals.MeshVisual that used to fill in.

class vispy.visuals.EllipseVisual(center=None, color='black', border_color=None, border_width=1, radius=(0.1, 0.1), start_angle=0.0, span_angle=360.0, num_segments=100, **kwargs)[source]

Bases: vispy.visuals.polygon.PolygonVisual

Displays a 2D ellipse

Parameters:

center : array

Center of the ellipse

color : instance of Color

The face color to use.

border_color : instance of Color

The border color to use.

border_width: float

The width of the border in pixels Line widths > 1px are only guaranteed to work when using border_method=’agg’ method.

radius : float | tuple

Radius or radii of the ellipse Defaults to (0.1, 0.1)

start_angle : float

Start angle of the ellipse in degrees Defaults to 0.

span_angle : float

Span angle of the ellipse in degrees Defaults to 360.

num_segments : int

Number of segments to be used to draw the ellipse Defaults to 100

**kwargs : dict

Keyword arguments to pass to PolygonVisual.

center

The center of the ellipse

num_segments

The number of segments in the ellipse.

radius

The start radii of the ellipse.

span_angle

The angular span of the ellipse.

start_angle

The start start_angle of the ellipse.

class vispy.visuals.GraphVisual(adjacency_mat=None, directed=False, layout=None, animate=False, line_color=None, line_width=None, arrow_type=None, arrow_size=None, node_symbol=None, node_size=None, border_color=None, face_color=None, border_width=None)[source]

Bases: vispy.visuals.visual.CompoundVisual

Visual for displaying graphs or networks.

Parameters:

adjacency_mat : array or sparse

The adjacency matrix of the graph.

directed : bool

Whether the graph is directed or not. If True, then this visual will draw arrows for the directed edges.

layout : str

They layout to use.

animate : bool

Whether or not to animate.

line_color : str or vispy.color.colormap.ColorMap

The color to use for the edges.

line_width : number

The edge thickness.

arrow_type : str

The kind of arrow head to use. See vispy.visuals.ArrowHead for more information.

arrow_size : number

The size of the arrow head.

node_symbol : string

The marker to use for nodes. See vispy.visuals.MarkersVisual for more information.

node_size : number

The size of the node

border_color : str or vispy.color.colormap.ColorMap

The border color for nodes.

face_color : str or vispy.color.colormap.ColorMap

The face color for nodes.

border_width : number

The border size for nodes.

set_data(adjacency_mat=None, **kwargs)[source]

Set the data

Parameters:

adjacency_mat : ndarray | None

The adjacency matrix.

**kwargs : dict

Keyword arguments to pass to the arrows.

class vispy.visuals.GridLinesVisual(scale=(1, 1), color='w')[source]

Bases: vispy.visuals.image.ImageVisual

Displays regularly spaced grid lines in any coordinate system and at any scale.

Parameters:

scale : tuple

The scale factors to apply when determining the spacing of grid lines.

color : Color

The base color for grid lines. The final color may have its alpha channel modified.

class vispy.visuals.GridMeshVisual(xs, ys, zs, colors=None, shading='smooth', **kwargs)[source]

Bases: vispy.visuals.mesh.MeshVisual

Displays a mesh in a Cartesian grid about x,y,z coordinates.

This makes it simple to generate a mesh from e.g. the output of numpy.meshgrid.

All arguments are optional, though they can be changed individually later with the set_data method.

Parameters:

xs : ndarray

A 2d array of x coordinates for the vertices of the mesh. Must have the same dimensions as ys and zs.

ys : ndarray

A 2d array of y coordinates for the vertices of the mesh. Must have the same dimensions as xs and zs.

zs : ndarray

A 2d array of z coordinates for the vertices of the mesh. Must have the same dimensions as xs and ys.

colors : ndarray | None

The colors of the points of the mesh. Should be either a (width, height, 4) array of rgba colors at each grid point or a (width, height, 3) array of rgb colors at each grid point. Defaults to None, in which case the default color of a MeshVisual is used.

shading : str | None

Same as for the MeshVisual class. Defaults to ‘smooth’.

**kwargs :

Other arguments are passed directly to MeshVisual.

set_data(xs=None, ys=None, zs=None, colors=None)[source]

Update the mesh data.

Parameters:

xs : ndarray | None

A 2d array of x coordinates for the vertices of the mesh.

ys : ndarray | None

A 2d array of y coordinates for the vertices of the mesh.

zs : ndarray | None

A 2d array of z coordinates for the vertices of the mesh.

colors : ndarray | None

The color at each point of the mesh. Must have shape (width, height, 4) or (width, height, 3) for rgba or rgb color definitions respectively.

class vispy.visuals.HistogramVisual(data, bins=10, color='w', orientation='h')[source]

Bases: vispy.visuals.mesh.MeshVisual

Visual that calculates and displays a histogram of data

Parameters:

data : array-like

Data to histogram. Currently only 1D data is supported.

bins : int | array-like

Number of bins, or bin edges.

color : instance of Color

Color of the histogram.

orientation : {‘h’, ‘v’}

Orientation of the histogram.

class vispy.visuals.ImageVisual(data=None, method='auto', grid=(1, 1), cmap='viridis', clim='auto', interpolation='nearest', **kwargs)[source]

Bases: vispy.visuals.visual.Visual

Visual subclass displaying an image.

Parameters:

data : ndarray

ImageVisual data. Can be shape (M, N), (M, N, 3), or (M, N, 4).

method : str

Selects method of rendering image in case of non-linear transforms. Each method produces similar results, but may trade efficiency and accuracy. If the transform is linear, this parameter is ignored and a single quad is drawn around the area of the image.

  • ‘auto’: Automatically select ‘impostor’ if the image is drawn with a nonlinear transform; otherwise select ‘subdivide’.
  • ‘subdivide’: ImageVisual is represented as a grid of triangles with texture coordinates linearly mapped.
  • ‘impostor’: ImageVisual is represented as a quad covering the entire view, with texture coordinates determined by the transform. This produces the best transformation results, but may be slow.

grid: tuple (rows, cols)

If method=’subdivide’, this tuple determines the number of rows and columns in the image grid.

cmap : str | ColorMap

Colormap to use for luminance images.

clim : str | tuple

Limits to use for the colormap. Can be ‘auto’ to auto-set bounds to the min and max of the data.

interpolation : str

Selects method of image interpolation. Makes use of the two Texture2D interpolation methods and the available interpolation methods defined in vispy/gloo/glsl/misc/spatial_filters.frag

  • ‘nearest’: Default, uses ‘nearest’ with Texture2D interpolation.
  • ‘bilinear’: uses ‘linear’ with Texture2D interpolation.
  • ‘hanning’, ‘hamming’, ‘hermite’, ‘kaiser’, ‘quadric’, ‘bicubic’,
    ‘catrom’, ‘mitchell’, ‘spline16’, ‘spline36’, ‘gaussian’, ‘bessel’, ‘sinc’, ‘lanczos’, ‘blackman’

**kwargs : dict

Keyword arguments to pass to Visual.

Notes

The colormap functionality through cmap and clim are only used if the data are 2D.

set_data(image)[source]

Set the data

Parameters:

image : array-like

The image data.

class vispy.visuals.InfiniteLineVisual(pos=None, color=(1.0, 1.0, 1.0, 1.0), vertical=True, **kwargs)[source]

Bases: vispy.visuals.visual.Visual

Infinite horizontal or vertical line for 2D plots.

Parameters:

pos : float

Position of the line along the axis.

color : list, tuple, or array

The color to use when drawing the line. If an array is given, it must be of shape (1, 4) and provide one rgba color per vertex.

vertical:

True for drawing a vertical line, False for an horizontal line

set_data(pos=None, color=None)[source]

Set the data

Parameters:

pos : float

Position of the line along the axis.

color : list, tuple, or array

The color to use when drawing the line. If an array is given, it must be of shape (1, 4) and provide one rgba color per vertex.

class vispy.visuals.IsocurveVisual(data=None, levels=None, color_lev=None, clim=None, **kwargs)[source]

Bases: vispy.visuals.line.line.LineVisual

Displays an isocurve of a 2D scalar array.

Parameters:

data : ndarray | None

2D scalar array.

levels : ndarray, shape (Nlev,) | None

The levels at which the isocurve is constructed from “data”.

color_lev : Color, colormap name, tuple, list or array

The color to use when drawing the line. If a list is given, it must be of shape (Nlev), if an array is given, it must be of shape (Nlev, …). and provide one color per level (rgba, colorname).

clim : tuple

(min, max) limits to apply when mapping level values through a colormap.

**kwargs : dict

Keyword arguments to pass to LineVisual.

levels

The threshold at which the isocurve is constructed from the 2D data.

set_data(data)[source]

Set the scalar array data

Parameters:

data : ndarray

A 2D array of scalar values. The isocurve is constructed to show all locations in the scalar field equal to self.levels.

class vispy.visuals.IsolineVisual(vertices=None, tris=None, data=None, levels=None, color_lev=None, **kwargs)[source]

Bases: vispy.visuals.line.line.LineVisual

Isocurves of a tri mesh with data at vertices at different levels.

Parameters:

vertices : ndarray, shape (Nv, 3) | None

Vertex coordinates.

tris : ndarray, shape (Nf, 3) | None

Indices into the vertex array.

data : ndarray, shape (Nv,) | None

scalar at vertices

levels : ndarray, shape (Nlev,) | None

The levels at which the isocurve is constructed from “data”.

color_lev : Color, tuple, colormap name or array

The color to use when drawing the line. If an array is given, it must be of shape (Nlev, 4) and provide one rgba color by level.

**kwargs : dict

Keyword arguments to pass to LineVisual.

data

The mesh data

levels

The threshold at which the isocurves are constructed from the data.

set_color(color)[source]

Set the color

Parameters:

color : instance of Color

The color to use.

set_data(vertices=None, tris=None, data=None)[source]

Set the data

Parameters:

vertices : ndarray, shape (Nv, 3) | None

Vertex coordinates.

tris : ndarray, shape (Nf, 3) | None

Indices into the vertex array.

data : ndarray, shape (Nv,) | None

scalar at vertices

class vispy.visuals.IsosurfaceVisual(data=None, level=None, vertex_colors=None, face_colors=None, color=(0.5, 0.5, 1, 1), **kwargs)[source]

Bases: vispy.visuals.mesh.MeshVisual

Displays an isosurface of a 3D scalar array.

Parameters:

data : ndarray | None

3D scalar array.

level: float | None

The level at which the isosurface is constructed from data.

vertex_colors : ndarray | None

The vertex colors to use.

face_colors : ndarray | None

The face colors to use.

color : ndarray | None

The color to use.

**kwargs : dict

Keyword arguments to pass to the mesh construction.

level

The threshold at which the isosurface is constructed from the 3D data.

set_data(data=None, vertex_colors=None, face_colors=None, color=None)[source]

Set the scalar array data

Parameters:

data : ndarray

A 3D array of scalar values. The isosurface is constructed to show all locations in the scalar field equal to self.level.

vertex_colors : array-like | None

Colors to use for each vertex.

face_colors : array-like | None

Colors to use for each face.

color : instance of Color

The color to use.

class vispy.visuals.LinePlotVisual(data=None, color='k', symbol=None, line_kind='-', width=1.0, marker_size=10.0, edge_color='k', face_color='w', edge_width=1.0, connect='strip')[source]

Bases: vispy.visuals.visual.CompoundVisual

Visual displaying a plot line with optional markers.

Parameters:

data : array-like

Arguments can be passed as (Y,), (X, Y), (X, Y, Z) or np.array((X, Y)), np.array((X, Y, Z)).

color : instance of Color

Color of the line.

symbol : str

Marker symbol to use.

line_kind : str

Kind of line to draw. For now, only solid lines ('-') are supported.

width : float

Line width.

marker_size : float

Marker size. If size == 0 markers will not be shown.

edge_color : instance of Color

Color of the marker edge.

face_color : instance of Color

Color of the marker face.

edge_width : float

Edge width of the marker.

connect : str | array

See LineVisual.

**kwargs : keyword arguments

Argements to pass to the super class.

See also

LineVisual, MarkersVisual, marker_types

Examples

All of these syntaxes will work:

>>> LinePlotVisual(y_vals)
>>> LinePlotVisual(x_vals, y_vals)
>>> LinePlotVisual(xy_vals)
set_data(data=None, **kwargs)[source]

Set the line data

Parameters:

data : array-like

The data.

**kwargs : dict

Keywoard arguments to pass to MarkerVisual and LineVisal.

class vispy.visuals.LineVisual(pos=None, color=(0.5, 0.5, 0.5, 1), width=1, connect='strip', method='gl', antialias=False)[source]

Bases: vispy.visuals.visual.CompoundVisual

Line visual

Parameters:

pos : array

Array of shape (…, 2) or (…, 3) specifying vertex coordinates.

color : Color, tuple, or array

The color to use when drawing the line. If an array is given, it must be of shape (…, 4) and provide one rgba color per vertex. Can also be a colormap name, or appropriate Function.

width:

The width of the line in px. Line widths > 1px are only guaranteed to work when using ‘agg’ method.

connect : str or array

Determines which vertices are connected by lines.

  • “strip” causes the line to be drawn with each vertex connected to the next.
  • “segments” causes each pair of vertices to draw an independent line segment
  • numpy arrays specify the exact set of segment pairs to connect.

method : str

Mode to use for drawing.

  • “agg” uses anti-grain geometry to draw nicely antialiased lines with proper joins and endcaps.
  • “gl” uses OpenGL’s built-in line rendering. This is much faster, but produces much lower-quality results and is not guaranteed to obey the requested line width or join/endcap styles.

antialias : bool

Enables or disables antialiasing. For method=’gl’, this specifies whether to use GL’s line smoothing, which may be unavailable or inconsistent on some platforms.

method

The current drawing method

set_data(pos=None, color=None, width=None, connect=None)[source]

Set the data used to draw this visual.

Parameters:

pos : array

Array of shape (…, 2) or (…, 3) specifying vertex coordinates.

color : Color, tuple, or array

The color to use when drawing the line. If an array is given, it must be of shape (…, 4) and provide one rgba color per vertex.

width:

The width of the line in px. Line widths < 1 px will be rounded up to 1 px when using the ‘gl’ method.

connect : str or array

Determines which vertices are connected by lines.

  • “strip” causes the line to be drawn with each vertex connected to the next.
  • “segments” causes each pair of vertices to draw an independent line segment
  • int numpy arrays specify the exact set of segment pairs to connect.
  • bool numpy arrays specify which _adjacent_ pairs to connect.
class vispy.visuals.LinearRegionVisual(pos=None, color=[1.0, 1.0, 1.0, 1.0], vertical=True, **kwargs)[source]

Bases: vispy.visuals.visual.Visual

Infinite horizontal or vertical region for 2D plots.

Parameters:

pos : list, tuple or numpy array

Bounds of the region along the axis. len(pos) must be >=2.

color : list, tuple, or array

The color to use when drawing the line. It must have a shape of (1, 4) for a single color region or (len(pos), 4) for a multicolor region.

vertical:

True for drawing a vertical region, False for an horizontal region

set_data(pos=None, color=None)[source]

Set the data

Parameters:

pos : list, tuple or numpy array

Bounds of the region along the axis. len(pos) must be >=2.

color : list, tuple, or array

The color to use when drawing the line. It must have a shape of (1, 4) for a single color region or (len(pos), 4) for a multicolor region.

class vispy.visuals.MarkersVisual(**kwargs)[source]

Bases: vispy.visuals.visual.Visual

Visual displaying marker symbols.

set_data(pos=None, symbol='o', size=10.0, edge_width=1.0, edge_width_rel=None, edge_color='black', face_color='white', scaling=False)[source]

Set the data used to display this visual.

Parameters:

pos : array

The array of locations to display each symbol.

symbol : str

The style of symbol to draw (see Notes).

size : float or array

The symbol size in px.

edge_width : float | None

The width of the symbol outline in pixels.

edge_width_rel : float | None

The width as a fraction of marker size. Exactly one of edge_width and edge_width_rel must be supplied.

edge_color : Color | ColorArray

The color used to draw each symbol outline.

face_color : Color | ColorArray

The color used to draw each symbol interior.

scaling : bool

If set to True, marker scales when rezooming.

Notes

Allowed style strings are: disc, arrow, ring, clobber, square, diamond, vbar, hbar, cross, tailed_arrow, x, triangle_up, triangle_down, and star.

class vispy.visuals.MeshVisual(vertices=None, faces=None, vertex_colors=None, face_colors=None, color=(0.5, 0.5, 1, 1), vertex_values=None, meshdata=None, shading=None, mode='triangles', **kwargs)[source]

Bases: vispy.visuals.visual.Visual

Mesh visual

Parameters:

vertices : array-like | None

The vertices.

faces : array-like | None

The faces.

vertex_colors : array-like | None

Colors to use for each vertex.

face_colors : array-like | None

Colors to use for each face.

color : instance of Color

The color to use.

vertex_values : array-like | None

The values to use for each vertex (for colormapping).

meshdata : instance of MeshData | None

The meshdata.

shading : str | None

Shading to use.

mode : str

The drawing mode.

**kwargs : dict

Keyword arguments to pass to Visual.

ambient_light_color

The ambient light color

color

The uniform color for this mesh

light_dir

The light direction

mesh_data

The mesh data

mode

The triangle mode used to draw this mesh.

Options are:

  • ‘triangles’: Draw one triangle for every three vertices (eg, [1,2,3], [4,5,6], [7,8,9)
  • ‘triangle_strip’: Draw one strip for every vertex excluding the first two (eg, [1,2,3], [2,3,4], [3,4,5])
  • ‘triangle_fan’: Draw each triangle from the first vertex and the last two vertices (eg, [1,2,3], [1,3,4], [1,4,5])
set_data(vertices=None, faces=None, vertex_colors=None, face_colors=None, color=None, vertex_values=None, meshdata=None)[source]

Set the mesh data

Parameters:

vertices : array-like | None

The vertices.

faces : array-like | None

The faces.

vertex_colors : array-like | None

Colors to use for each vertex.

face_colors : array-like | None

Colors to use for each face.

color : instance of Color

The color to use.

vertex_values : array-like | None

Values for each vertex.

meshdata : instance of MeshData | None

The meshdata.

shading

The shading method used.

shininess

The shininess

class vispy.visuals.PlaneVisual(width=1, height=1, width_segments=1, height_segments=1, direction='+z', vertex_colors=None, face_colors=None, color=(0.5, 0.5, 1, 1), edge_color=None)[source]

Bases: vispy.visuals.visual.CompoundVisual

Visual that displays a plane.

Parameters:

width : float

Plane width.

height : float

Plane height.

width_segments : int

Plane segments count along the width.

height_segments : float

Plane segments count along the height.

direction: unicode

{'-x', '+x', '-y', '+y', '-z', '+z'} Direction the plane will be facing.

vertex_colors : ndarray

Same as for MeshVisual class. See create_plane for vertex ordering.

face_colors : ndarray

Same as for MeshVisual class. See create_plane for vertex ordering.

color : Color

The Color to use when drawing the cube faces.

edge_color : tuple or Color

The Color to use when drawing the cube edges. If None, then no cube edges are drawn.

class vispy.visuals.PolygonVisual(pos=None, color='black', border_color=None, border_width=1, border_method='gl', triangulate=True, **kwargs)[source]

Bases: vispy.visuals.visual.CompoundVisual

Displays a 2D polygon

Parameters:

pos : array

Set of vertices defining the polygon.

color : str | tuple | list of colors

Fill color of the polygon.

border_color : str | tuple | list of colors

Border color of the polygon.

border_width : int

Border width in pixels. Line widths > 1px are only guaranteed to work when using border_method=’agg’ method.

border_method : str

Mode to use for drawing the border line (see LineVisual).

  • “agg” uses anti-grain geometry to draw nicely antialiased lines with proper joins and endcaps.
  • “gl” uses OpenGL’s built-in line rendering. This is much faster, but produces much lower-quality results and is not guaranteed to obey the requested line width or join/endcap styles.

triangulate : boolean

Triangulate the set of vertices

**kwargs : dict

Keyword arguments to pass to CompoundVisual.

border

The vispy.visuals.LineVisual that is owned by the PolygonVisual. It is used to draw the border of the polygon

border_color

The border color of the polygon.

color

The color of the polygon.

mesh

The vispy.visuals.MeshVisual that is owned by the PolygonVisual. It is used to fill in the polygon

pos

The vertex position of the polygon.

class vispy.visuals.RectangleVisual(center=None, color='black', border_color=None, border_width=1, height=1.0, width=1.0, radius=[0.0, 0.0, 0.0, 0.0], **kwargs)[source]

Bases: vispy.visuals.polygon.PolygonVisual

Displays a 2D rectangle with optional rounded corners

Parameters:

center : array

Center of the rectangle

color : instance of Color

The fill color to use.

border_color : instance of Color

The border color to use.

border_width : int

Border width in pixels. Line widths > 1px are only guaranteed to work when using border_method=’agg’ method.

height : float

Length of the rectangle along y-axis Defaults to 1.0

width : float

Length of the rectangle along x-axis Defaults to 1.0

radius : float | array

Radii of curvatures of corners in clockwise order from top-left Defaults to 0.

**kwargs : dict

Keyword arguments to pass to PolygonVisual.

center

The center of the ellipse

height

The height of the rectangle.

radius

The radius of curvature of rounded corners.

width

The width of the rectangle.

class vispy.visuals.RegularPolygonVisual(center=None, color='black', border_color=None, border_width=1, radius=0.1, sides=4, **kwargs)[source]

Bases: vispy.visuals.ellipse.EllipseVisual

Displays a regular polygon

Parameters:

center : array-like (x, y)

Center of the regular polygon

color : str | tuple | list of colors

Fill color of the polygon

border_color : str | tuple | list of colors

Border color of the polygon

border_width: float

The width of the border in pixels

radius : float

Radius of the regular polygon Defaults to 0.1

sides : int

Number of sides of the regular polygon

sides

The number of sides in the regular polygon.

class vispy.visuals.ScrollingLinesVisual(n_lines, line_size, dx, color=None, pos_offset=None, columns=None, cell_size=None)[source]

Bases: vispy.visuals.visual.Visual

Displays many line strips of equal length, with the option to add new vertex data to one end of the lines.

Parameters:

n_lines : int

The number of independent line strips to draw.

line_size : int

The number of samples in each line strip.

dx : float

The x distance between samples

color : array-like

An array of colors to assign to each line strip.

pos_offset : array-like

An array of x, y position offsets to apply to each line strip.

columns : int

Arrange line strips into a grid with this number of columns. This option is not compatible with pos_offset.

cell_size : tuple

The x, y distance between cells in the grid.

roll_data(data)[source]

Append new data to the right side of every line strip and remove as much data from the left.

Parameters:

data : array-like

A data array to append.

set_color(color)[source]

Set the array of colors for each line strip.

Parameters:

color : array-like

An array of rgba values.

set_data(index, data)[source]

Set the complete data for a single line strip.

Parameters:

index : int

The index of the line strip to be replaced.

data : array-like

The data to assign to the selected line strip.

set_pos_offset(po)[source]

Set the array of position offsets for each line strip.

Parameters:

po : array-like

An array of xy offset values.

class vispy.visuals.SpectrogramVisual(x, n_fft=256, step=None, fs=1.0, window='hann', color_scale='log', cmap='cubehelix', clim='auto')[source]

Bases: vispy.visuals.image.ImageVisual

Calculate and show a spectrogram

Parameters:

x : array-like

1D signal to operate on. If len(x) < n_fft, x will be zero-padded to length n_fft.

n_fft : int

Number of FFT points. Much faster for powers of two.

step : int | None

Step size between calculations. If None, n_fft // 2 will be used.

fs : float

The sample rate of the data.

window : str | None

Window function to use. Can be 'hann' for Hann window, or None for no windowing.

color_scale : {‘linear’, ‘log’}

Scale to apply to the result of the STFT. 'log' will use 10 * log10(power).

cmap : str

Colormap name.

clim : str | tuple

Colormap limits. Should be 'auto' or a two-element tuple of min and max values.

freqs

The spectrogram frequencies

class vispy.visuals.SphereVisual(radius=1.0, cols=30, rows=30, depth=30, subdivisions=3, method='latitude', vertex_colors=None, face_colors=None, color=(0.5, 0.5, 1, 1), edge_color=None, **kwargs)[source]

Bases: vispy.visuals.visual.CompoundVisual

Visual that displays a sphere

Parameters:

radius : float

The size of the sphere.

cols : int

Number of cols that make up the sphere mesh (for method=’latitude’ and ‘cube’).

rows : int

Number of rows that make up the sphere mesh (for method=’latitude’ and ‘cube’).

depth : int

Number of depth segments that make up the sphere mesh (for method=’cube’).

subdivisions : int

Number of subdivisions to perform (for method=’ico’).

method : str

Method for generating sphere. Accepts ‘latitude’ for latitude-longitude, ‘ico’ for icosahedron, and ‘cube’ for cube based tessellation.

vertex_colors : ndarray

Same as for MeshVisual class. See create_sphere for vertex ordering.

face_colors : ndarray

Same as for MeshVisual class. See create_sphere for vertex ordering.

color : Color

The Color to use when drawing the sphere faces.

edge_color : tuple or Color

The Color to use when drawing the sphere edges. If None, then no sphere edges are drawn.

border

The vispy.visuals.MeshVisual that used to draw the border.

mesh

The vispy.visuals.MeshVisual that used to fil in.

class vispy.visuals.SurfacePlotVisual(x=None, y=None, z=None, colors=None, **kwargs)[source]

Bases: vispy.visuals.mesh.MeshVisual

Displays a surface plot on a regular x,y grid

Parameters:

x : ndarray | None

1D array of values specifying the x positions of vertices in the grid. If None, values will be assumed to be integers.

y : ndarray | None

1D array of values specifying the x positions of vertices in the grid. If None, values will be assumed to be integers.

z : ndarray

2D array of height values for each grid vertex.

colors : ndarray

(width, height, 4) array of vertex colors.

Notes

All arguments are optional.

Note that if vertex positions are updated, the normal vectors for each triangle must be recomputed. This is somewhat expensive if the surface was initialized with smooth=False and very expensive if smooth=True. For faster performance, initialize with compute_normals=False and use per-vertex colors or a material that does not require normals.

set_data(x=None, y=None, z=None, colors=None)[source]

Update the data in this surface plot.

Parameters:

x : ndarray | None

1D array of values specifying the x positions of vertices in the grid. If None, values will be assumed to be integers.

y : ndarray | None

1D array of values specifying the x positions of vertices in the grid. If None, values will be assumed to be integers.

z : ndarray

2D array of height values for each grid vertex.

colors : ndarray

(width, height, 4) array of vertex colors.

class vispy.visuals.TextVisual(text=None, color='black', bold=False, italic=False, face='OpenSans', font_size=12, pos=[0, 0, 0], rotation=0.0, anchor_x='center', anchor_y='center', font_manager=None)[source]

Bases: vispy.visuals.visual.Visual

Visual that displays text

Parameters:

text : str | list of str

Text to display. Can also be a list of strings. Note: support for list of str might be removed soon in favor of text collections.

color : instance of Color

Color to use.

bold : bool

Bold face.

italic : bool

Italic face.

face : str

Font face to use.

font_size : float

Point size to use.

pos : tuple | list of tuple

Position (x, y) or (x, y, z) of the text. Can also be a list of tuple if text is a list.

rotation : float

Rotation (in degrees) of the text clockwise.

anchor_x : str

Horizontal text anchor.

anchor_y : str

Vertical text anchor.

font_manager : object | None

Font manager to use (can be shared if the GLContext is shared).

color

The color of the text

font_size

The font size (in points) of the text

pos

The position of the text anchor in the local coordinate frame

rotation

The rotation of the text (clockwise, in degrees)

text

The text string

class vispy.visuals.TubeVisual(points, radius=1.0, closed=False, color='purple', tube_points=8, shading='smooth', vertex_colors=None, face_colors=None, mode='triangles')[source]

Bases: vispy.visuals.mesh.MeshVisual

Displays a tube around a piecewise-linear path.

The tube mesh is corrected following its Frenet curvature and torsion such that it varies smoothly along the curve, including if the tube is closed.

Parameters:

points : ndarray

An array of (x, y, z) points describing the path along which the tube will be extruded.

radius : float

The radius of the tube. Defaults to 1.0.

closed : bool

Whether the tube should be closed, joining the last point to the first. Defaults to False.

color : Color | ColorArray

The color(s) to use when drawing the tube. The same color is applied to each vertex of the mesh surrounding each point of the line. If the input is a ColorArray, the argument will be cycled; for instance if ‘red’ is passed then the entire tube will be red, or if [‘green’, ‘blue’] is passed then the points will alternate between these colours. Defaults to ‘purple’.

tube_points : int

The number of points in the circle-approximating polygon of the tube’s cross section. Defaults to 8.

shading : str | None

Same as for the MeshVisual class. Defaults to ‘smooth’.

vertex_colors: ndarray | None

Same as for the MeshVisual class.

face_colors: ndarray | None

Same as for the MeshVisual class.

mode : str

Same as for the MeshVisual class. Defaults to ‘triangles’.

class vispy.visuals.Visual(vcode='', fcode='', program=None, vshare=None)[source]

Bases: vispy.visuals.visual.BaseVisual

Base class for all visuals that can be drawn using a single shader program.

This class creates a MultiProgram, which is an object that behaves like a normal shader program (you can assign shader code, upload values, set template variables, etc.) but internally manages multiple ModularProgram instances, one per view.

Subclasses generally only need to reimplement _compute_bounds, _prepare_draw, and _prepare_transforms.

Parameters:

vcode : str

Vertex shader code.

fcode : str

Fragment shader code.

program : instance of Program | None

The program to use. If None, a program will be constructed using vcode and fcode.

vshare : instance of VisualShare | None

The visual share, if necessary.

attach(filt, view=None)[source]

Attach a Filter to this visual

Each filter modifies the appearance or behavior of the visual.

Parameters:

filt : object

The filter to attach.

view : instance of VisualView | None

The view to use.

detach(filt, view=None)[source]

Detach a filter.

Parameters:

filt : object

The filter to detach.

view : instance of VisualView | None

The view to use.

set_gl_state(preset=None, **kwargs)[source]

Define the set of GL state parameters to use when drawing

Parameters:

preset : str

Preset to use.

**kwargs : dict

Keyword arguments to gloo.set_state.

update_gl_state(*args, **kwargs)[source]

Modify the set of GL state parameters to use when drawing

Parameters:

*args : tuple

Arguments.

**kwargs : dict

Keyword argments.

class vispy.visuals.VolumeVisual(vol, clim=None, method='mip', threshold=None, relative_step_size=0.8, cmap='grays', emulate_texture=False)[source]

Bases: vispy.visuals.visual.Visual

Displays a 3D Volume

Parameters:

vol : ndarray

The volume to display. Must be ndim==3.

clim : tuple of two floats | None

The contrast limits. The values in the volume are mapped to black and white corresponding to these values. Default maps between min and max.

method : {‘mip’, ‘translucent’, ‘additive’, ‘iso’}

The render method to use. See corresponding docs for details. Default ‘mip’.

threshold : float

The threshold to use for the isosurface render method. By default the mean of the given volume is used.

relative_step_size : float

The relative step size to step through the volume. Default 0.8. Increase to e.g. 1.5 to increase performance, at the cost of quality.

cmap : str

Colormap to use.

emulate_texture : bool

Use 2D textures to emulate a 3D texture. OpenGL ES 2.0 compatible, but has lower performance on desktop platforms.

clim

The contrast limits that were applied to the volume data. Settable via set_data().

method

The render method to use

Current options are:

  • translucent: voxel colors are blended along the view ray until the result is opaque.
  • mip: maxiumum intensity projection. Cast a ray and display the maximum value that was encountered.
  • additive: voxel colors are added along the view ray until the result is saturated.
  • iso: isosurface. Cast a ray until a certain threshold is encountered. At that location, lighning calculations are performed to give the visual appearance of a surface.
relative_step_size

The relative step size used during raycasting.

Larger values yield higher performance at reduced quality. If set > 2.0 the ray skips entire voxels. Recommended values are between 0.5 and 1.5. The amount of quality degredation depends on the render method.

set_data(vol, clim=None)[source]

Set the volume data.

Parameters:

vol : ndarray

The 3D volume.

clim : tuple | None

Colormap limits to use. None will use the min and max values.

threshold

The threshold value to apply for the isosurface render method.

class vispy.visuals.XYZAxisVisual(**kwargs)[source]

Bases: vispy.visuals.line.line.LineVisual

Simple 3D axis for indicating coordinate system orientation. Axes are x=red, y=green, z=blue.


vispy.visuals.filters

class vispy.visuals.filters.Clipper(bounds=(0, 0, 1, 1), transform=None)[source]

Bases: object

Clips visual output to a rectangular region.

bounds

The clipping boundaries.

This must be a tuple (x, y, w, h) in a clipping coordinate system that is defined by the transform property.

transform

The transform that maps from framebuffer coordinates to clipping coordinates.

class vispy.visuals.filters.PickingFilter(id_=None)[source]

Bases: object

Filter used to color visuals by a picking ID.

Note that the ID color uses the alpha channel, so this may not be used with blending enabled.

color

The RGBA color that will be drawn to the framebuffer for visuals that use this filter.


vispy.visuals.transforms

Provides classes representing different transform types suitable for use with visuals and scenes.

class vispy.visuals.transforms.NullTransform[source]

Bases: vispy.visuals.transforms.base_transform.BaseTransform

Transform having no effect on coordinates (identity transform).

imap(coords)[source]

Inverse map coordinates

Parameters:

coords : array-like

Coordinates to inverse map.

map(coords)[source]

Map coordinates

Parameters:

coords : array-like

Coordinates to map.

class vispy.visuals.transforms.STTransform(scale=None, translate=None)[source]

Bases: vispy.visuals.transforms.base_transform.BaseTransform

Transform performing only scale and translate, in that order.

Parameters:

scale : array-like

Scale factors for X, Y, Z axes.

translate : array-like

Scale factors for X, Y, Z axes.

classmethod from_mapping(x0, x1)[source]

Create an STTransform from the given mapping

See set_mapping for details.

Parameters:

x0 : array-like

Start.

x1 : array-like

End.

Returns:

t : instance of STTransform

The transform.

imap(coords)[source]

Invert map coordinates

Parameters:

coords : array-like

Coordinates to inverse map.

Returns:

coords : ndarray

Coordinates.

map(coords)[source]

Map coordinates

Parameters:

coords : array-like

Coordinates to map.

Returns:

coords : ndarray

Coordinates.

move(move)[source]

Change the translation of this transform by the amount given.

Parameters:

move : array-like

The values to be added to the current translation of the transform.

set_mapping(x0, x1, update=True)[source]

Configure this transform such that it maps points x0 => x1

Parameters:

x0 : array-like, shape (2, 2) or (2, 3)

Start location.

x1 : array-like, shape (2, 2) or (2, 3)

End location.

update : bool

If False, then the update event is not emitted.

Examples

For example, if we wish to map the corners of a rectangle:

>>> p1 = [[0, 0], [200, 300]]

onto a unit cube:

>>> p2 = [[-1, -1], [1, 1]]

then we can generate the transform as follows:

>>> tr = STTransform()
>>> tr.set_mapping(p1, p2)
>>> assert tr.map(p1)[:,:2] == p2  # test
zoom(zoom, center=(0, 0, 0), mapped=True)[source]

Update the transform such that its scale factor is changed, but the specified center point is left unchanged.

Parameters:

zoom : array-like

Values to multiply the transform’s current scale factors.

center : array-like

The center point around which the scaling will take place.

mapped : bool

Whether center is expressed in mapped coordinates (True) or unmapped coordinates (False).

class vispy.visuals.transforms.MatrixTransform(matrix=None)[source]

Bases: vispy.visuals.transforms.base_transform.BaseTransform

Affine transformation class

Parameters:

matrix : array-like | None

4x4 array to use for the transform.

imap(coords)[source]

Inverse map coordinates

Parameters:

coords : array-like

Coordinates to inverse map.

Returns:

coords : ndarray

Coordinates.

map(coords)[source]

Map coordinates

Parameters:

coords : array-like

Coordinates to map.

Returns:

coords : ndarray

Coordinates.

rotate(angle, axis)[source]

Rotate the matrix by some angle about a given axis.

The rotation is applied after the transformations already present in the matrix.

Parameters:

angle : float

The angle of rotation, in degrees.

axis : array-like

The x, y and z coordinates of the axis vector to rotate around.

scale(scale, center=None)[source]

Scale the matrix about a given origin.

The scaling is applied after the transformations already present in the matrix.

Parameters:

scale : array-like

Scale factors along x, y and z axes.

center : array-like or None

The x, y and z coordinates to scale around. If None, (0, 0, 0) will be used.

set_frustum(l, r, b, t, n, f)[source]

Set the frustum

Parameters:

l : float

Left.

r : float

Right.

b : float

Bottom.

t : float

Top.

n : float

Near.

f : float

Far.

set_mapping(points1, points2)[source]

Set to a 3D transformation matrix that maps points1 onto points2.

Parameters:

points1 : array-like, shape (4, 3)

Four starting 3D coordinates.

points2 : array-like, shape (4, 3)

Four ending 3D coordinates.

set_ortho(l, r, b, t, n, f)[source]

Set ortho transform

Parameters:

l : float

Left.

r : float

Right.

b : float

Bottom.

t : float

Top.

n : float

Near.

f : float

Far.

set_perspective(fov, aspect, near, far)[source]

Set the perspective

Parameters:

fov : float

Field of view.

aspect : float

Aspect ratio.

near : float

Near location.

far : float

Far location.

translate(pos)[source]

Translate the matrix

The translation is applied after the transformations already present in the matrix.

Parameters:

pos : arrayndarray

Position to translate by.

class vispy.visuals.transforms.MatrixTransform(matrix=None)[source]

Bases: vispy.visuals.transforms.base_transform.BaseTransform

Affine transformation class

Parameters:

matrix : array-like | None

4x4 array to use for the transform.

imap(coords)[source]

Inverse map coordinates

Parameters:

coords : array-like

Coordinates to inverse map.

Returns:

coords : ndarray

Coordinates.

map(coords)[source]

Map coordinates

Parameters:

coords : array-like

Coordinates to map.

Returns:

coords : ndarray

Coordinates.

rotate(angle, axis)[source]

Rotate the matrix by some angle about a given axis.

The rotation is applied after the transformations already present in the matrix.

Parameters:

angle : float

The angle of rotation, in degrees.

axis : array-like

The x, y and z coordinates of the axis vector to rotate around.

scale(scale, center=None)[source]

Scale the matrix about a given origin.

The scaling is applied after the transformations already present in the matrix.

Parameters:

scale : array-like

Scale factors along x, y and z axes.

center : array-like or None

The x, y and z coordinates to scale around. If None, (0, 0, 0) will be used.

set_frustum(l, r, b, t, n, f)[source]

Set the frustum

Parameters:

l : float

Left.

r : float

Right.

b : float

Bottom.

t : float

Top.

n : float

Near.

f : float

Far.

set_mapping(points1, points2)[source]

Set to a 3D transformation matrix that maps points1 onto points2.

Parameters:

points1 : array-like, shape (4, 3)

Four starting 3D coordinates.

points2 : array-like, shape (4, 3)

Four ending 3D coordinates.

set_ortho(l, r, b, t, n, f)[source]

Set ortho transform

Parameters:

l : float

Left.

r : float

Right.

b : float

Bottom.

t : float

Top.

n : float

Near.

f : float

Far.

set_perspective(fov, aspect, near, far)[source]

Set the perspective

Parameters:

fov : float

Field of view.

aspect : float

Aspect ratio.

near : float

Near location.

far : float

Far location.

translate(pos)[source]

Translate the matrix

The translation is applied after the transformations already present in the matrix.

Parameters:

pos : arrayndarray

Position to translate by.

class vispy.visuals.transforms.LogTransform(base=None)[source]

Bases: vispy.visuals.transforms.base_transform.BaseTransform

Transform perfoming logarithmic transformation on three axes.

Maps (x, y, z) => (log(base.x, x), log(base.y, y), log(base.z, z))

No transformation is applied for axes with base == 0.

If base < 0, then the inverse function is applied: x => base.x ** x

Parameters:

base : array-like

Base for the X, Y, Z axes.

base

base is a tuple (x, y, z) containing the log base that should be applied to each axis of the input vector. If any axis has a base <= 0, then that axis is not affected.

imap(arg, *args, **kwargs)[source]

Function

Parameters:

arg : array-like

Argument to convert.

*args : tuple

Arguments.

**kwargs : dict

Keyword arguments.

Returns:

value : object

The return value of the function.

map(arg, *args, **kwargs)[source]

Function

Parameters:

arg : array-like

Argument to convert.

*args : tuple

Arguments.

**kwargs : dict

Keyword arguments.

Returns:

value : object

The return value of the function.

class vispy.visuals.transforms.PolarTransform[source]

Bases: vispy.visuals.transforms.base_transform.BaseTransform

Polar transform

Maps (theta, r, z) to (x, y, z), where x = r*cos(theta) and y = r*sin(theta).

imap(arg, *args, **kwargs)[source]

Function

Parameters:

arg : array-like

Argument to convert.

*args : tuple

Arguments.

**kwargs : dict

Keyword arguments.

Returns:

value : object

The return value of the function.

map(arg, *args, **kwargs)[source]

Function

Parameters:

arg : array-like

Argument to convert.

*args : tuple

Arguments.

**kwargs : dict

Keyword arguments.

Returns:

value : object

The return value of the function.

class vispy.visuals.transforms.ChainTransform(*transforms)[source]

Bases: vispy.visuals.transforms.base_transform.BaseTransform

BaseTransform subclass that performs a sequence of transformations in order. Internally, this class uses shaders.FunctionChain to generate its glsl_map and glsl_imap functions.

Arguments:

transforms : list of BaseTransform instances
See transforms property.
append(tr)[source]

Add a new transform to the end of this chain.

Parameters:

tr : instance of Transform

The transform to use.

imap(coords)[source]

Inverse map coordinates

Parameters:

coords : array-like

Coordinates to inverse map.

Returns:

coords : ndarray

Coordinates.

map(coords)[source]

Map coordinates

Parameters:

coords : array-like

Coordinates to map.

Returns:

coords : ndarray

Coordinates.

prepend(tr)[source]

Add a new transform to the beginning of this chain.

Parameters:

tr : instance of Transform

The transform to use.

simplified

A simplified representation of the same transformation.

transforms

The list of transform that make up the transform chain.

The order of transforms is given such that the last transform in the list is the first to be invoked when mapping coordinates through the chain.

For example, the following two mappings are equivalent:

# Map coordinates through individual transforms:
trans1 = STTransform(scale=(2, 3), translate=(0, 1))
trans2 = PolarTransform()
mapped = trans1.map(trans2.map(coords))

# Equivalent mapping through chain:
chain = ChainTransform([trans1, trans2])
mapped = chain.map(coords)
class vispy.visuals.transforms.TransformSystem(canvas=None, dpi=None)[source]

Bases: object

TransformSystem encapsulates information about the coordinate systems needed to draw a Visual.

Visual rendering operates in six coordinate systems:

  • Visual - arbitrary local coordinate frame of the visual. Vertex buffers used by the visual are usually specified in this coordinate system.
  • Scene - This is an isometric coordinate system used mainly for lighting calculations.
  • Document - This coordinate system has units of _logical_ pixels, and should usually represent the pixel coordinates of the canvas being drawn to. Visuals use this coordinate system to make measurements for font size, line width, and in general anything that is specified in physical units (px, pt, mm, in, etc.). In most circumstances, this is exactly the same as the canvas coordinate system.
  • Canvas - This coordinate system represents the logical pixel coordinates of the canvas. It has its origin in the top-left corner of the canvas, and is typically the coordinate system that mouse and touch events are reported in. Note that, by convention, _logical_ pixels are not necessarily the same size as the _physical_ pixels in the framebuffer that is being rendered to.
  • Framebuffer - The buffer coordinate system has units of _physical_ pixels, and should usually represent the coordinates of the current framebuffer (on the canvas or an FBO) being rendered to. Visuals use this coordinate system primarily for antialiasing calculations. It is also the coorinate system used by glFragCoord. In most cases, this will have the same scale as the document and canvas coordinate systems because the active framebuffer is the back buffer of the canvas, and the canvas will have _logical_ and _physical_ pixels of the same size. However, the scale may be different in the case of high-resolution displays, or when rendering to an off-screen framebuffer with different scaling or boundaries than the canvas.
  • Render - This coordinate system is the obligatory system for vertices returned by a vertex shader. It has coordinates (-1, -1) to (1, 1) across the current glViewport. In OpenGL terminology, this is called clip coordinates.
Parameters:

canvas : Canvas

The canvas being drawn to.

dpi : float

The dot-per-inch resolution of the document coordinate system. By default this is set to the resolution of the canvas.

Notes

By default, TransformSystems are configured such that the document coordinate system matches the logical pixels of the canvas,

Examples

1. To convert local vertex coordinates to normalized device coordinates in the vertex shader, we first need a vertex shader that supports configurable transformations:

vec4 a_position;
void main() {
    gl_Position = $transform(a_position);
}

Next, we supply the complete chain of transforms when drawing the visual:

def draw(tr_sys):
tr = tr_sys.get_full_transform() self.program[‘transform’] = tr.shader_map() self.program[‘a_position’] = self.vertex_buffer self.program.draw(‘triangles’)

2. Draw a line whose width is given in mm. To start, we need normal vectors for each vertex, which tell us the direction the vertex should move in order to set the line width:

vec4 a_position;
vec4 a_normal;
float u_line_width;
float u_dpi;
void main() {
    // map vertex position and normal vector to the document cs
    vec4 doc_pos = $visual_to_doc(a_position);
    vec4 doc_normal = $visual_to_doc(a_position + a_normal) - doc_pos;

    // Use DPI to convert mm line width to logical pixels
    float px_width = (u_line_width / 25.4) * dpi;

    // expand by line width
    doc_pos += normalize(doc_normal) * px_width;

    // finally, map the remainder of the way to normalized device
    // coordinates.
    gl_Position = $doc_to_render(a_position);
}

In this case, we need to access the transforms independently, so get_full_transform() is not useful here:

def draw(tr_sys):
    # Send two parts of the full transform separately
    self.program['visual_to_doc'] = tr_sys.visual_to_doc.shader_map()
    doc_to_render = (tr_sys.framebuffer_transform *
                     tr_sys.document_transform)
    self.program['visual_to_doc'] = doc_to_render.shader_map()

    self.program['u_line_width'] = self.line_width
    self.program['u_dpi'] = tr_sys.dpi
    self.program['a_position'] = self.vertex_buffer
    self.program['a_normal'] = self.normal_buffer
    self.program.draw('triangles')
  1. Draw a triangle with antialiasing at the edge.
  2. Using inverse transforms in the fragment shader
canvas

The Canvas being drawn to.

canvas_transform

Transform mapping from canvas coordinate frame to framebuffer coordinate frame.

configure(viewport=None, fbo_size=None, fbo_rect=None, canvas=None)[source]

Automatically configure the TransformSystem:

  • canvas_transform maps from the Canvas logical pixel coordinate system to the framebuffer coordinate system, taking into account the logical/physical pixel scale factor, current FBO position, and y-axis inversion.
  • framebuffer_transform maps from the current GL viewport on the framebuffer coordinate system to clip coordinates (-1 to 1).
Parameters:

viewport : tuple or None

The GL viewport rectangle (x, y, w, h). If None, then it is assumed to cover the entire canvas.

fbo_size : tuple or None

The size of the active FBO. If None, then it is assumed to have the same size as the canvas’s framebuffer.

fbo_rect : tuple or None

The position and size (x, y, w, h) of the FBO in the coordinate system of the canvas’s framebuffer. If None, then the bounds are assumed to cover the entire active framebuffer.

canvas : Canvas instance

Optionally set the canvas for this TransformSystem. See the canvas property.

document_transform

Transform mapping from document coordinate frame to the framebuffer (physical pixel) coordinate frame.

dpi

Physical resolution of the document coordinate system (dots per inch).

framebuffer_transform

Transform mapping from pixel coordinate frame to rendering coordinate frame.

get_transform(map_from='visual', map_to='render')[source]

Return a transform mapping between any two coordinate systems.

Parameters:

map_from : str

The starting coordinate system to map from. Must be one of: visual, scene, document, canvas, framebuffer, or render.

map_to : str

The ending coordinate system to map to. Must be one of: visual, scene, document, canvas, framebuffer, or render.

scene_transform

Transform mapping from scene coordinate frame to document coordinate frame.

visual_transform

Transform mapping from visual local coordinate frame to scene coordinate frame.

class vispy.visuals.transforms.PanZoomTransform(canvas=None, aspect=None, **kwargs)[source]

Bases: vispy.visuals.transforms.linear.STTransform

Pan-zoom transform

Parameters:

canvas : instance of Canvas | None

The canvas to attch to.

aspect : float | None

The aspect ratio to apply.

**kwargs : dict

Keyword arguments to pass to the underlying STTransform.

attach(canvas)[source]

Attach this tranform to a canvas

Parameters:

canvas : instance of Canvas

The canvas.

on_mouse_move(event)[source]

Mouse move handler

Parameters:

event : instance of Event

The event.

on_mouse_wheel(event)[source]

Mouse wheel handler

Parameters:

event : instance of Event

The event.

on_resize(event)[source]

Resize handler

Parameters:

event : instance of Event

The event.