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.AxisVisual(pos, 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), **kwargs)

Bases: vispy.visuals.visual.Visual

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.

**kwargs : dict

Keyword arguments to pass to Visual.

Methods

attach(filt) Attach a Filter to this visual
bounds(mode, axis) Get the bounds
detach(filt) Detach a filter
draw(transforms) Draw the visual
set_gl_state([preset]) Define the set of GL state parameters to use when drawing
update() Emit an event to inform listeners that this Visual needs to be redrawn.
update_gl_state(*args, **kwargs) Modify the set of GL state parameters to use when drawing
bounds(mode, axis)

Get the bounds

Parameters:

mode : str

Describes the type of boundary requested. Can be "visual", "data", or "mouse".

axis : 0, 1, 2

The axis along which to measure the bounding values, in x-y-z order.

draw(transforms)

Draw the visual

Parameters:

transforms : instance of TransformSystem

The transforms to use.

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)

Bases: vispy.visuals.mesh.MeshVisual

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.

Methods

attach(filt) Attach a Filter to this visual
bounds(mode, axis) Get the bounds
detach(filt) Detach a filter
draw(transforms) Draw the visual
mesh_data_changed()
set_data([vertices, faces, vertex_colors, ...]) Set the mesh data
set_gl_state([preset]) Define the set of GL state parameters to use when drawing
update() Emit an event to inform listeners that this Visual needs to be redrawn.
update_gl_state(*args, **kwargs) Modify the set of GL state parameters to use when drawing
draw(transforms)

Draw the visual

Parameters:

transforms : instance of TransformSystem

The transforms to use.

class vispy.visuals.ColorBarVisual(center_pos, halfdim, cmap, orientation, label_str='', clim=(0.0, 1.0), border_width=1.0, border_color='black', **kwargs)

Bases: vispy.visuals.visual.Visual

Visual subclass displaying a colorbar

Parameters:

center_pos : tuple (x, y)

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

halfdim : tuple (half_width, half_height)

Half the dimensions of the colorbar measured from the center. That way, the total dimensions of the colorbar is (x - half_width) to (x + half_width) and (y - half_height) to (y + half_height)

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

label_str : str

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

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

Methods

attach(filt) Attach a Filter to this visual
bounds(mode, axis) Return the (min, max) bounding values describing the location of this node in its local coordinate system.
detach(filt) Detach a filter
draw(transforms) Draw the visual
set_gl_state([preset]) Define the set of GL state parameters to use when drawing
update() Emit an event to inform listeners that this Visual needs to be redrawn.
update_gl_state(*args, **kwargs) Modify the set of GL state parameters to use when drawing
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

draw(transforms)

Draw the visual

Parameters:

transforms : instance of TransformSystem

The transforms to use.

label

The vispy.visuals.TextVisual associated with the label

ticks

The vispy.visuals.TextVisual associated with the ticks

Returns:

ticks: [vispy.visual.TextVisual] :

The array is of length 2

class vispy.visuals.CubeVisual(size=1.0, vertex_colors=None, face_colors=None, color=(0.5, 0.5, 1, 1), edge_color=None)

Bases: vispy.visuals.mesh.MeshVisual

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.

Methods

attach(filt) Attach a Filter to this visual
bounds(mode, axis) Get the bounds
detach(filt) Detach a filter
draw(transforms) Draw the visual
mesh_data_changed()
set_data([vertices, faces, vertex_colors, ...]) Set the mesh data
set_gl_state([preset]) Define the set of GL state parameters to use when drawing
update() Emit an event to inform listeners that this Visual needs to be redrawn.
update_gl_state(*args, **kwargs) Modify the set of GL state parameters to use when drawing
draw(transforms)

Draw the visual

Parameters:

transforms : instance of TransformSystem

The transforms to use.

class vispy.visuals.EllipseVisual(pos=None, color='black', border_color=None, radius=(0.1, 0.1), start_angle=0.0, span_angle=360.0, num_segments=100, **kwargs)

Bases: vispy.visuals.polygon.PolygonVisual

Displays a 2D ellipse

Parameters:

pos : array

Center of the ellipse

color : instance of Color

The face color to use.

border_color : instance of Color

The border color to use.

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 0.

num_segments : int

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

Methods

attach(filt) Attach a Filter to this visual
bounds(mode, axis) Return the (min, max) bounding values describing the location of this node in its local coordinate system.
detach(filt) Detach a filter
draw(transforms) Draw the visual
set_gl_options(*args, **kwargs)
set_gl_state([preset]) Define the set of GL state parameters to use when drawing
update() Emit an event to inform listeners that this Visual needs to be redrawn.
update_gl_options(*args, **kwargs)
update_gl_state(*args, **kwargs) Modify the set of GL state parameters to use when drawing
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.GridLinesVisual(scale=(1, 1), **kwargs)

Bases: vispy.visuals.visual.Visual

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

Parameters:

scale : tuple

The scale to use.

Methods

attach(filt) Attach a Filter to this visual
bounds(mode, axis) Return the (min, max) bounding values describing the location of this node in its local coordinate system.
detach(filt) Detach a filter
draw(transforms) Draw the visual
set_gl_state([preset]) Define the set of GL state parameters to use when drawing
update() Emit an event to inform listeners that this Visual needs to be redrawn.
update_gl_state(*args, **kwargs) Modify the set of GL state parameters to use when drawing
draw(transforms)

Draw the visual

Parameters:

transforms : instance of TransformSystem

The transforms to use.

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

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.

Methods

attach(filt) Attach a Filter to this visual
bounds(mode, axis) Get the bounds
detach(filt) Detach a filter
draw(transforms) Draw the visual
mesh_data_changed()
set_data([vertices, faces, vertex_colors, ...]) Set the mesh data
set_gl_state([preset]) Define the set of GL state parameters to use when drawing
update() Emit an event to inform listeners that this Visual needs to be redrawn.
update_gl_state(*args, **kwargs) Modify the set of GL state parameters to use when drawing
class vispy.visuals.ImageVisual(data=None, method='auto', grid=(10, 10), cmap='cubehelix', clim='auto', **kwargs)

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.

**kwargs : dict

Keyword arguments to pass to Visual.

Notes

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

Methods

attach(filt) Attach a Filter to this visual
bounds(mode, axis) Get the bounds
detach(filt) Detach a filter
draw(transforms) Draw the visual
set_data(image) Set the data
set_gl_state([preset]) Define the set of GL state parameters to use when drawing
update() Emit an event to inform listeners that this Visual needs to be redrawn.
update_gl_state(*args, **kwargs) Modify the set of GL state parameters to use when drawing
bounds(mode, axis)

Get the bounds

Parameters:

mode : str

Describes the type of boundary requested. Can be "visual", "data", or "mouse".

axis : 0, 1, 2

The axis along which to measure the bounding values, in x-y-z order.

draw(transforms)

Draw the visual

Parameters:

transforms : instance of TransformSystem

The transforms to use.

set_data(image)

Set the data

Parameters:

image : array-like

The image data.

class vispy.visuals.IsocurveVisual(data=None, level=None, **kwargs)

Bases: vispy.visuals.line.line.LineVisual

Displays an isocurve of a 2D scalar array.

Parameters:

data : ndarray | None

2D scalar array.

level: float | None :

The level at which the isocurve is constructed from data.

Methods

attach(filt) Attach a Filter to this visual
bounds(mode, axis) Get the bounds
detach(filt) Detach a filter
draw(transforms) Draw the visual
set_data(data) Set the scalar array data
set_gl_state(**kwargs)
update() Emit an event to inform listeners that this Visual needs to be redrawn.
update_gl_state(**kwargs)
draw(transforms)

Draw the visual

Parameters:

transforms : instance of TransformSystem

The transforms to use.

level

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

set_data(data)

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.level.

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

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.

Methods

attach(filt) Attach a Filter to this visual
bounds(mode, axis) Get the bounds
detach(filt) Detach a filter
draw(transforms) Draw the visual
set_color(color) Set the color
set_data([vertices, tris, data]) Set the data
set_gl_state(**kwargs)
update() Emit an event to inform listeners that this Visual needs to be redrawn.
update_gl_state(**kwargs)
data

The mesh data

draw(transforms)

Draw the visual

Parameters:

transforms : instance of TransformSystem

The transforms to use.

levels

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

set_color(color)

Set the color

Parameters:

color : instance of Color

The color to use.

set_data(vertices=None, tris=None, data=None)

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, **kwargs)

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.

Methods

attach(filt) Attach a Filter to this visual
bounds(mode, axis) Get the bounds
detach(filt) Detach a filter
draw(transforms) Draw the visual
mesh_data_changed()
set_data(data) Set the scalar array data
set_gl_state([preset]) Define the set of GL state parameters to use when drawing
update() Emit an event to inform listeners that this Visual needs to be redrawn.
update_gl_state(*args, **kwargs) Modify the set of GL state parameters to use when drawing
draw(transforms)

Draw the visual

Parameters:

transforms : instance of TransformSystem

The transforms to use.

level

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

set_data(data)

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.

class vispy.visuals.LinePlotVisual(data, color='k', symbol='o', line_kind='-', width=1.0, marker_size=10.0, edge_color='k', face_color='w', edge_width=1.0, connect='strip', **kwargs)

Bases: vispy.visuals.visual.Visual

Visual displaying a plot line with optional markers.

Parameters:

data : array-like

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

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)

Methods

attach(filt) Attach a Filter to this visual
bounds(mode, axis) Get the bounds
detach(filt) Detach a filter
draw(transforms) Draw the visual
set_data(data, **kwargs) Set the line data
set_gl_state([preset]) Define the set of GL state parameters to use when drawing
update() Emit an event to inform listeners that this Visual needs to be redrawn.
update_gl_state(*args, **kwargs) Modify the set of GL state parameters to use when drawing
bounds(mode, axis)

Get the bounds

Parameters:

mode : str

Describes the type of boundary requested. Can be "visual", "data", or "mouse".

axis : 0, 1, 2

The axis along which to measure the bounding values, in x-y-z order.

draw(transforms)

Draw the visual

Parameters:

transforms : instance of TransformSystem

The transforms to use.

set_data(data, **kwargs)

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)

Bases: vispy.visuals.visual.Visual

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.

Methods

attach(filt) Attach a Filter to this visual
bounds(mode, axis) Get the bounds
detach(filt) Detach a filter
draw(transforms) Draw the visual
set_data([pos, color, width, connect]) Set the data used to draw this visual.
set_gl_state(**kwargs)
update() Emit an event to inform listeners that this Visual needs to be redrawn.
update_gl_state(**kwargs)
bounds(mode, axis)

Get the bounds

Parameters:

mode : str

Describes the type of boundary requested. Can be "visual", "data", or "mouse".

axis : 0, 1, 2

The axis along which to measure the bounding values, in x-y-z order.

draw(transforms)

Draw the visual

Parameters:

transforms : instance of TransformSystem

The transforms to use.

method

The current drawing method

set_data(pos=None, color=None, width=None, connect=None)

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 > 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
  • int numpy arrays specify the exact set of segment pairs to connect.
  • bool numpy arrays specify which _adjacent_ pairs to connect.
class vispy.visuals.MarkersVisual

Bases: vispy.visuals.visual.Visual

Visual displaying marker symbols.

Methods

attach(filt) Attach a Filter to this visual
bounds(mode, axis) Get the bounds
detach(filt) Detach a filter
draw(transforms) Draw the visual
set_data([pos, symbol, size, edge_width, ...]) Set the data used to display this visual.
set_gl_state([preset]) Define the set of GL state parameters to use when drawing
set_symbol([symbol]) Set the symbol
update() Emit an event to inform listeners that this Visual needs to be redrawn.
update_gl_state(*args, **kwargs) Modify the set of GL state parameters to use when drawing
bounds(mode, axis)

Get the bounds

Parameters:

mode : str

Describes the type of boundary requested. Can be "visual", "data", or "mouse".

axis : 0, 1, 2

The axis along which to measure the bounding values, in x-y-z order.

draw(transforms)

Draw the visual

Parameters:

transforms : instance of TransformSystem

The transforms to use.

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)

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.

set_symbol(symbol='o')

Set the symbol

Parameters:

symbol : str

The symbol.

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

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.

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.

Methods

attach(filt) Attach a Filter to this visual
bounds(mode, axis) Get the bounds
detach(filt) Detach a filter
draw(transforms) Draw the visual
mesh_data_changed()
set_data([vertices, faces, vertex_colors, ...]) Set the mesh data
set_gl_state([preset]) Define the set of GL state parameters to use when drawing
update() Emit an event to inform listeners that this Visual needs to be redrawn.
update_gl_state(*args, **kwargs) Modify the set of GL state parameters to use when drawing
bounds(mode, axis)

Get the bounds

Parameters:

mode : str

Describes the type of boundary requested. Can be "visual", "data", or "mouse".

axis : 0, 1, 2

The axis along which to measure the bounding values, in x-y-z order.

color

The uniform color for this mesh.

This value is only used if per-vertex or per-face colors are not specified.

draw(transforms)

Draw the visual

Parameters:

transforms : instance of TransformSystem

The transforms to use.

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, meshdata=None)

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.

meshdata : instance of MeshData | None

The meshdata.

shading

The shading method used.

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)

Bases: vispy.visuals.mesh.MeshVisual

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.

Methods

attach(filt) Attach a Filter to this visual
bounds(mode, axis) Get the bounds
detach(filt) Detach a filter
draw(transforms) Draw the visual
mesh_data_changed()
set_data([vertices, faces, vertex_colors, ...]) Set the mesh data
set_gl_state([preset]) Define the set of GL state parameters to use when drawing
update() Emit an event to inform listeners that this Visual needs to be redrawn.
update_gl_state(*args, **kwargs) Modify the set of GL state parameters to use when drawing
draw(transforms)

Draw the visual

Parameters:

transforms : instance of TransformSystem

The transforms to use.

class vispy.visuals.PolygonVisual(pos=None, color='black', border_color=None, border_width=1, **kwargs)

Bases: vispy.visuals.visual.Visual

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.

**kwargs : dict

Keyword arguments to pass to PolygonVisual.

Methods

attach(filt) Attach a Filter to this visual
bounds(mode, axis) Return the (min, max) bounding values describing the location of this node in its local coordinate system.
detach(filt) Detach a filter
draw(transforms) Draw the visual
set_gl_options(*args, **kwargs)
set_gl_state([preset]) Define the set of GL state parameters to use when drawing
update() Emit an event to inform listeners that this Visual needs to be redrawn.
update_gl_options(*args, **kwargs)
update_gl_state(*args, **kwargs) Modify the set of GL state parameters to use when drawing
border_color

The border color of the polygon.

color

The color of the polygon.

draw(transforms)

Draw the visual

Parameters:

transforms : instance of TransformSystem

The transforms to use.

pos

The vertex position of the polygon.

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

Bases: vispy.visuals.polygon.PolygonVisual

Displays a 2D rectangle with optional rounded corners

Parameters:

pos : array

Center of the rectangle

color : instance of Color

The fill color to use.

border_color : instance of Color

The border color to use.

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.

Methods

attach(filt) Attach a Filter to this visual
bounds(mode, axis) Return the (min, max) bounding values describing the location of this node in its local coordinate system.
detach(filt) Detach a filter
draw(transforms) Draw the visual
set_gl_options(*args, **kwargs)
set_gl_state([preset]) Define the set of GL state parameters to use when drawing
update() Emit an event to inform listeners that this Visual needs to be redrawn.
update_gl_options(*args, **kwargs)
update_gl_state(*args, **kwargs) Modify the set of GL state parameters to use when drawing
height

The height of the rectangle.

radius

The radius of curvature of rounded corners.

width

The width of the rectangle.

class vispy.visuals.RegularPolygonVisual(pos=None, color='black', border_color=None, radius=0.1, sides=4, **kwargs)

Bases: vispy.visuals.ellipse.EllipseVisual

Displays a regular polygon

Parameters:

pos : array

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

radius : float

Radius of the regular polygon Defaults to 0.1

sides : int

Number of sides of the regular polygon

Methods

attach(filt) Attach a Filter to this visual
bounds(mode, axis) Return the (min, max) bounding values describing the location of this node in its local coordinate system.
detach(filt) Detach a filter
draw(transforms) Draw the visual
set_gl_options(*args, **kwargs)
set_gl_state([preset]) Define the set of GL state parameters to use when drawing
update() Emit an event to inform listeners that this Visual needs to be redrawn.
update_gl_options(*args, **kwargs)
update_gl_state(*args, **kwargs) Modify the set of GL state parameters to use when drawing
sides

The number of sides in the regular polygon.

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

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.

Methods

attach(filt) Attach a Filter to this visual
bounds(mode, axis) Get the bounds
detach(filt) Detach a filter
draw(transforms) Draw the visual
set_data(image) Set the data
set_gl_state([preset]) Define the set of GL state parameters to use when drawing
update() Emit an event to inform listeners that this Visual needs to be redrawn.
update_gl_state(*args, **kwargs) Modify the set of GL state parameters to use when drawing
freqs

The spectrogram frequencies

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

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.

Methods

attach(filt) Attach a Filter to this visual
bounds(mode, axis) Get the bounds
detach(filt) Detach a filter
draw(transforms) Draw the visual
generate_faces()
mesh_data_changed()
set_data([x, y, z, colors]) Update the data in this surface plot.
set_gl_state([preset]) Define the set of GL state parameters to use when drawing
update() Emit an event to inform listeners that this Visual needs to be redrawn.
update_gl_state(*args, **kwargs) Modify the set of GL state parameters to use when drawing
set_data(x=None, y=None, z=None, colors=None)

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, 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, **kwargs)

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).

Methods

attach(filt) Attach a Filter to this visual
bounds(mode, axis) Return the (min, max) bounding values describing the location of this node in its local coordinate system.
detach(filt) Detach a filter
draw(transforms) Draw the Text
set_gl_state([preset]) Define the set of GL state parameters to use when drawing
update() Emit an event to inform listeners that this Visual needs to be redrawn.
update_gl_state(*args, **kwargs) Modify the set of GL state parameters to use when drawing
color

The color of the text

draw(transforms)

Draw the Text

Parameters:

transforms : instance of TransformSystem

The transforms to use.

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')

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'.

Methods

attach(filt) Attach a Filter to this visual
bounds(mode, axis) Get the bounds
detach(filt) Detach a filter
draw(transforms) Draw the visual
mesh_data_changed()
set_data([vertices, faces, vertex_colors, ...]) Set the mesh data
set_gl_state([preset]) Define the set of GL state parameters to use when drawing
update() Emit an event to inform listeners that this Visual needs to be redrawn.
update_gl_state(*args, **kwargs) Modify the set of GL state parameters to use when drawing
draw(transforms)

Draw the visual

Parameters:

transforms : instance of TransformSystem

The transforms to use.

class vispy.visuals.Visual

Bases: object

Abstract class representing a drawable object.

At a minimum, Visual subclasses should extend the draw() method.

Events:

update : Event
Emitted when the visual has changed and needs to be redrawn.
bounds_change : Event
Emitted when the bounds of the visual have changed.

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.

Methods

attach(filt) Attach a Filter to this visual
bounds(mode, axis) Return the (min, max) bounding values describing the location of this node in its local coordinate system.
detach(filt) Detach a filter
draw(transforms) Draw this visual now.
set_gl_state([preset]) Define the set of GL state parameters to use when drawing
update() Emit an event to inform listeners that this Visual needs to be redrawn.
update_gl_state(*args, **kwargs) Modify the set of GL state parameters to use when drawing
attach(filt)

Attach a Filter to this visual

Each filter modifies the appearance or behavior of the visual.

Parameters:

filt : object

The filter to attach.

bounds(mode, axis)

Return the (min, max) bounding values describing the location of this node in its local coordinate system.

Parameters:

mode : str

Describes the type of boundary requested. Can be "visual", "data", or "mouse".

axis : 0, 1, 2

The axis along which to measure the bounding values, in x-y-z order.

Returns:

None or (min, max) tuple. :

Notes

This is used primarily to allow automatic ViewBox zoom/pan. By default, this method returns None which indicates the object should be ignored for automatic zooming along axis.

A scenegraph may also use this information to cull visuals from the display list.

detach(filt)

Detach a filter

Parameters:

filt : object

The filter to detach.

draw(transforms)

Draw this visual now.

The default implementation calls gloo.set_state().

This function is called automatically when the visual needs to be drawn as part of a scenegraph, or when calling SceneCanvas.draw_visual(...). It is uncommon to call this method manually.

The transforms argument is a TransformSystem instance that provides access to transforms that the visual may use to determine its relationship to the document coordinate system (which provides physical measurements) and the framebuffer coordinate system (which is necessary for antialiasing calculations).

Vertex transformation can be done either on the CPU using Transform.map(), or on the GPU using the GLSL functions generated by Transform.shader_map().

Parameters:

transforms : instance of TransformSystem

The transforms to use.

set_gl_state(preset=None, **kwargs)

Define the set of GL state parameters to use when drawing

Parameters:

preset : str

Preset to use.

**kwargs : dict

Keyword argments to use.

update()

Emit an event to inform listeners that this Visual needs to be redrawn.

update_gl_state(*args, **kwargs)

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)

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 isosurafce 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.

Methods

attach(filt) Attach a Filter to this visual
bounds(mode, axis) Get the visual bounds
detach(filt) Detach a filter
draw(transforms) Draw the visual
set_data(vol[, clim]) Set the volume data.
set_gl_state([preset]) Define the set of GL state parameters to use when drawing
update() Emit an event to inform listeners that this Visual needs to be redrawn.
update_gl_state(*args, **kwargs) Modify the set of GL state parameters to use when drawing
bounds(mode, axis)

Get the visual bounds

Parameters:

mode : str

The mode.

axis : int

The axis number.

Returns:

bounds : tuple

The lower and upper bounds.

clim

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

draw(transforms)

Draw the visual

Parameters:

transforms : instance of TransformSystem

The transforms to use.

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)

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)

Bases: vispy.visuals.line.line.LineVisual

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

Methods

attach(filt) Attach a Filter to this visual
bounds(mode, axis) Get the bounds
detach(filt) Detach a filter
draw(transforms) Draw the visual
set_data([pos, color, width, connect]) Set the data used to draw this visual.
set_gl_state(**kwargs)
update() Emit an event to inform listeners that this Visual needs to be redrawn.
update_gl_state(**kwargs)

vispy.visuals.filters

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

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)

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

Bases: vispy.visuals.transforms.base_transform.BaseTransform

Transform having no effect on coordinates (identity transform).

Methods

imap(coords) Inverse map coordinates
map(coords) Map coordinates
shader_imap() see shader_map.
shader_map() Return a shader Function that accepts only a single vec4 argument and defines new attributes / uniforms supplying the Function with any static input.
update() Called to inform any listeners that this transform has changed.
imap(coords)

Inverse map coordinates

Parameters:

coords : array-like

Coordinates to inverse map.

map(coords)

Map coordinates

Parameters:

coords : array-like

Coordinates to map.

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

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.

Methods

as_affine()
from_mapping(x0, x1) Create an STTransform from the given mapping
imap(coords) Invert map coordinates
map(coords) Map coordinates
move(move) Change the translation of this transform by the amount given.
set_mapping(x0, x1) Configure this transform such that it maps points x0 => x1
shader_imap()
shader_map()
update() Called to inform any listeners that this transform has changed.
zoom(zoom[, center, mapped]) Update the transform such that its scale factor is changed, but the specified center point is left unchanged.
classmethod from_mapping(x0, x1)

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)

Invert map coordinates

Parameters:

coords : array-like

Coordinates to inverse map.

Returns:

coords : ndarray

Coordinates.

map(coords)

Map coordinates

Parameters:

coords : array-like

Coordinates to map.

Returns:

coords : ndarray

Coordinates.

move(move)

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)

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.

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)

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.AffineTransform(matrix=None)

Bases: vispy.visuals.transforms.base_transform.BaseTransform

Affine transformation class

Parameters:

matrix : array-like | None

4x4 array to use for the transform.

Methods

imap(coords) Inverse map coordinates
map(coords) Map coordinates
reset()
rotate(angle, axis) Rotate the matrix by some angle about a given axis.
scale(scale[, center]) Scale the matrix about a given origin.
set_mapping(points1, points2) Set to a 3D transformation matrix that maps points1 onto points2.
set_ortho(l, r, b, t, n, f) Set ortho transform
shader_imap()
shader_map()
translate(pos) Translate the matrix
update() Called to inform any listeners that this transform has changed.
imap(coords)

Inverse map coordinates

Parameters:

coords : array-like

Coordinates to inverse map.

Returns:

coords : ndarray

Coordinates.

map(coords)

Map coordinates

Parameters:

coords : array-like

Coordinates to map.

Returns:

coords : ndarray

Coordinates.

rotate(angle, axis)

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)

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_mapping(points1, points2)

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)

Set ortho transform

Parameters:

l : float

Left.

r : float

Right.

b : float

Bottom.

t : float

Top.

n : float

Near.

f : float

Far.

translate(pos)

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.PerspectiveTransform(matrix=None)

Bases: vispy.visuals.transforms.linear.AffineTransform

Matrix transform that also implements perspective division.

Parameters:

matrix : array-like | None

4x4 array to use for the transform.

Methods

imap(coords) Inverse map coordinates
map(coords) Map coordinates
reset()
rotate(angle, axis) Rotate the matrix by some angle about a given axis.
scale(scale[, center]) Scale the matrix about a given origin.
set_frustum(l, r, b, t, n, f) Set the frustum
set_mapping(points1, points2) Set to a 3D transformation matrix that maps points1 onto points2.
set_ortho(l, r, b, t, n, f) Set ortho transform
set_perspective(fov, aspect, near, far) Set the perspective
shader_imap()
shader_map()
translate(pos) Translate the matrix
update() Called to inform any listeners that this transform has changed.
set_frustum(l, r, b, t, n, f)

Set the frustum

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)

Set the perspective

Parameters:

fov : float

Field of view.

aspect : float

Aspect ratio.

near : float

Near location.

far : float

Far location.

class vispy.visuals.transforms.LogTransform(base=None)

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.

Methods

imap(arg, *args, **kwargs) Function
map(arg, *args, **kwargs) Function
shader_imap()
shader_map()
update() Called to inform any listeners that this transform has changed.
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)

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)

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

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).

Methods

imap(arg, *args, **kwargs) Function
map(arg, *args, **kwargs) Function
shader_imap() see shader_map.
shader_map() Return a shader Function that accepts only a single vec4 argument and defines new attributes / uniforms supplying the Function with any static input.
update() Called to inform any listeners that this transform has changed.
imap(arg, *args, **kwargs)

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)

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)

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.

Attributes

glsl_imap
glsl_map

Methods

append(tr) Add a new transform to the end of this chain.
flat() Return a simplified chain by expanding any nested chains.
imap(coords) Inverse map coordinates
map(coords) Map coordinates
prepend(tr) Add a new transform to the beginning of this chain.
shader_imap()
shader_map()
simplified() Return a simplified chain by joining adjacent transforms.
update() Called to inform any listeners that this transform has changed.
append(tr)

Add a new transform to the end of this chain.

Parameters:

tr : instance of Transform

The transform to use.

flat()

Return a simplified chain by expanding any nested chains.

imap(coords)

Inverse map coordinates

Parameters:

coords : array-like

Coordinates to inverse map.

Returns:

coords : ndarray

Coordinates.

map(coords)

Map coordinates

Parameters:

coords : array-like

Coordinates to map.

Returns:

coords : ndarray

Coordinates.

prepend(tr)

Add a new transform to the beginning of this chain.

Parameters:

tr : instance of Transform

The transform to use.

simplified()

Return a simplified chain by joining adjacent transforms. If the result is a single transform, return that transform.

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, dpi=None)

Bases: object

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

Visual rendering operates in four coordinate systems:

  • Visual - arbitrary local coordinate frame of the visual. Vertex buffers used by the visual are usually specified in this coordinate system.
  • 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.). Note that, by convention, _logical_ pixels are not necessarily the same size as the _physical_ pixels in the framebuffer that is being rendered to.
  • Buffer - The buffer coordinate system has units of _physical_ pixels, and should usually represent the coordinates of the current framebuffer being rendered to. Visuals use this coordinate system primarily for antialiasing calculations. In most cases, this will have the same scale as the document coordinate system because the active framebuffer is the back buffer of the canvas, and the canvas will have _logical_ and _physical_ pixels of the same size. 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 vertexes returned by a vertex shader. It has coordinates (-1, -1) to (1, 1) across the current glViewport. In OpenGL terminology, this is called normalized device 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_to_render *
                     tr_sys.document_to_framebuffer)
    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
  1. Basic example, including checks for canvas resolution
  2. How to handle off-screen framebuffers

Methods

auto_configure() Automatically configure the TransformSystem:
get_full_transform() Convenience method that returns the composition of all three
auto_configure()

Automatically configure the TransformSystem:

  • document_to_framebuffer maps from the Canvas logical pixel coordinate system to the framebuffer coordinate system, assuming physical pixels of the same size. The y-axis is inverted in this transform.
  • framebuffer_to_render maps from the framebuffer coordinate system to normalized device coordinates (-1 to 1).
canvas

The Canvas being drawn to.

document_to_framebuffer

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_to_render

Transform mapping from pixel coordinate frame to rendering coordinate frame.

get_full_transform()

Convenience method that returns the composition of all three transforms:

framebuffer_to_render * document_to_framebuffer * visual_to_document

This is used for visuals that do not require physical measurements or antialiasing.

visual_to_document

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

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

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.

Methods

as_affine()
attach(canvas) Attach this tranform to a canvas
from_mapping(x0, x1) Create an STTransform from the given mapping
imap(coords) Invert map coordinates
map(coords) Map coordinates
move(move) Change the translation of this transform by the amount given.
on_mouse_move(event) Mouse move handler
on_mouse_wheel(event) Mouse wheel handler
on_resize(event) Resize handler
set_mapping(x0, x1) Configure this transform such that it maps points x0 => x1
shader_imap()
shader_map()
update() Called to inform any listeners that this transform has changed.
zoom(zoom[, center, mapped]) Update the transform such that its scale factor is changed, but the specified center point is left unchanged.
attach(canvas)

Attach this tranform to a canvas

Parameters:

canvas : instance of Canvas

The canvas.

on_mouse_move(event)

Mouse move handler

Parameters:

event : instance of Event

The event.

on_mouse_wheel(event)

Mouse wheel handler

Parameters:

event : instance of Event

The event.

on_resize(event)

Resize handler

Parameters:

event : instance of Event

The event.