anyplotlib.Plot3D#

class anyplotlib.Plot3D(geom_type, x, y, z, *, colormap='viridis', color='#4fc3f7', colors=None, point_size=4.0, linewidth=1.5, x_label='x', y_label='y', z_label='z', azimuth=-60.0, elevation=30.0, zoom=1.0, bounds=None, voxel_size=1.0, alpha=None, texture=None, gpu='auto')[source]#

Bases: _BasePlot

3-D plot panel.

Supports four geometry types:

  • 'surface' – triangulated surface, Z-coloured via colormap, or wrapped in an image with set_texture() (globes, star charts).

  • 'scatter' – point cloud; single colour or per-point colors.

  • 'line' – connected line through 3-D points.

  • 'voxels' – shaded translucent cubes at the given centres; voxels lying on a PlaneWidget slice render more opaque.

A single point can be emphasised with set_highlight() (e.g. the “current” orientation in an IPF explorer), and bounds= fixes the axes extents for origin-true geometry such as unit vectors on a sphere. Draggable PlaneWidget slice selectors are added with add_widget().

Created by Axes.plot_surface(), Axes.scatter3d(), and Axes.plot3d().

Not an anywidget. Holds state in _state dict; every mutation calls _push() which writes to the parent Figure’s panel trait.

Parameters:
add_widget(kind, **kwargs)[source]#

Add an interactive overlay widget to this 3-D panel.

Currently supports "plane" — a draggable axis-aligned slice plane (see PlaneWidget):

pw = vol.add_widget("plane", axis="z", position=24)

@pw.add_event_handler("pointer_move")
def on_drag(event):
    resliced(int(round(pw.position)))
Parameters:

kind (str)

remove_widget(wid)[source]#

Remove a widget by ID string or Widget instance.

Return type:

None

list_widgets()[source]#

Return a list of all active widget objects on this panel.

Return type:

list

set_voxel_alpha(alpha, slice_alpha=None)[source]#

Set voxel transparency (geom_type 'voxels').

Parameters:
  • alpha (float) – Base opacity (0–1) for voxels not on any plane widget.

  • slice_alpha (float, optional) – Opacity for voxels lying on a PlaneWidget slice. None keeps the current value (default 0.95).

Return type:

None

to_state_dict()[source]#
Return type:

dict

property gpu_active: bool#

True if this panel is currently rendering geometry on the GPU.

Reflects the JS renderer’s decision after the first frame: WebGPU is used only when available and when the panel’s gpu policy and point count call for it. Always False on the Canvas2D fallback path (no navigator.gpu, no adapter, device lost, or gpu=False).

set_colormap(name)[source]#

Set the surface colormap (ignored for scatter/line).

Parameters:

name (str)

Return type:

None

set_view(azimuth=None, elevation=None)[source]#

Set the camera azimuth (°) and/or elevation (°).

Uses a targeted field push so re-aiming the camera never re-transmits the panel’s geometry — important for large voxel/scatter panels.

Parameters:
Return type:

None

set_rotation(matrix=None)[source]#

Orient the data with a rotation matrix, independent of the camera.

The camera’s azimuth and elevation can only aim it — two degrees of freedom. An orientation has three: a crystal, a molecule, or a sample on a stage turns about every axis. matrix rotates the data about the centre of its bounds, and the camera then looks at the result, so set_rotation says how the object is turned and set_view() says where you stand to look at it.

Like set_view(), this is a targeted push: rotating a large surface or point cloud never re-sends its geometry or texture.

Parameters:

matrix ((3, 3) array-like, optional) – A proper rotation (orthonormal, determinant +1). Column j is where the data’s j-th axis points after rotating, so matrix @ v maps a data-frame direction into the rotated frame. None restores the identity.

Raises:

ValueError – If matrix is not 3×3, not orthonormal, or a reflection.

Return type:

None

See also

rotation

The current matrix, including drags made in the viewer.

set_drag_mode

Let the viewer edit the rotation by dragging.

property rotation: ndarray#

The current model rotation as a (3, 3) array.

Follows drags made in "rotate" mode (see set_drag_mode()) as well as set_rotation().

set_drag_mode(mode)[source]#

Choose what a left-button drag on the panel does.

Parameters:

mode ("orbit" | "rotate") – "orbit" (the default) moves the camera around the data. "rotate" turns the data under a fixed camera instead, editing rotation: horizontal and vertical motion roll the surface under the cursor like a trackball, and a drag with Shift held spins it about the line of sight — the third degree of freedom an orbit cannot reach. Every drag frame fires pointer_move and the release fires pointer_up, both with event.rotation set, so keep the pointer_move handler fast and do expensive work (re-simulating a pattern, say) on pointer_up.

Return type:

None

set_zoom(zoom)[source]#
Parameters:

zoom (float)

Return type:

None

reset_view()[source]#

Restore the camera to the angles/zoom set at construction time.

Return type:

None

set_xlabel(label, fontsize=None)[source]#

Set the x-axis label (mini-TeX allowed; default size 11 px).

Parameters:
Return type:

None

set_ylabel(label, fontsize=None)[source]#

Set the y-axis label (mini-TeX allowed; default size 11 px).

Parameters:
Return type:

None

set_zlabel(label, fontsize=None)[source]#

Set the z-axis label (mini-TeX allowed; default size 11 px).

Parameters:
Return type:

None

get_xlim()[source]#

Return the data x range as (xmin, xmax).

Return type:

tuple

get_ylim()[source]#

Return the data y range as (ymin, ymax).

Return type:

tuple

get_zlim()[source]#

Return the data z range as (zmin, zmax).

Return type:

tuple

set_data(x, y, z)[source]#

Replace the geometry data (same shape rules as the constructor).

Bounds given at construction time (bounds=) are preserved. An auto-mapped texture (set_texture() without uv=) follows the new grid, keeping the flip_v it was applied with; explicit UVs are kept and must still match the vertex count.

Return type:

None

set_texture(image, *, uv=None, alpha=1.0, shade=False, cull_backfaces=False, flip_v=False)[source]#

Wrap an image around this surface (geom_type == 'surface').

Each triangle is filled with the matching patch of image, so the picture follows the geometry as you orbit — a globe, a planet, or a star chart on the celestial sphere. By default the image is mapped parametrically: its left edge to the surface grid’s first column, its right edge to the last, its top row to the grid’s first row. Build the sphere with longitude along the columns and latitude down the rows and an equirectangular (plate-carrée) image lands exactly right.

Rendering goes through WebGPU when it is available and the surface has more than ~2k triangles (see the gpu argument to Axes.plot_surface()), which lifts the practical grid size from a few thousand triangles to hundreds of thousands. Without a GPU — or with alpha below 1, which needs the Canvas2D compositing path — every triangle is texture-mapped on the CPU instead, so prefer a coarse grid there and let the image carry the detail.

Parameters:
  • image (array-like, bytes, or path) – An (H, W, 3|4) colour array (uint8, or float 0–1 — a PIL image works too), the raw bytes of a PNG/JPEG/GIF/WebP, or a path to such a file. Encoded input is passed through untouched; arrays are PNG-compressed. Very large images cost wire size and decode time — 2048×1024 is plenty for a sphere.

  • uv ((U, V) or (N, 2) array, optional) – Explicit texture coordinates in 0–1, one per vertex, instead of the default parametric mapping. U/V may be given in the grid’s 2-D shape or already flattened.

  • alpha (float, optional) – Opacity of the whole textured surface, 0–1. Default 1. Below 1 the surface is composited as one translucent skin — whatever the panel draws behind it (a reference sphere, a scatter cloud) shows through, but the surface’s own far side does not.

  • shade (bool, optional) – Modulate the texture with diffuse lighting from the upper left. Default False (the image is reproduced faithfully); True gives a sphere its familiar lit look and makes relief read as relief.

  • cull_backfaces (bool, optional) – Skip triangles facing away from the camera. Default False. Set True for a closed surface (sphere, ellipsoid, blob) — it halves the drawing work with no visual change. On an open surface it makes the back side invisible, which is usually not what you want. Ignored on the WebGPU path, where the depth buffer resolves occlusion exactly and culling buys nothing.

  • flip_v (bool, optional) – Mirror the mapping vertically (v → 1 - v). Use when the image is stored bottom-up relative to the grid’s row order. Remembered for the auto mapping, so a later set_data() rebuilds the UVs with the same flip.

Raises:

ValueError – If this is not a 'surface' panel, alpha is outside [0, 1], image is not a decodable image, or uv does not cover every vertex.

Return type:

None

See also

clear_texture

Remove the texture and fall back to colormapped Z.

Examples

lat = np.linspace(np.pi / 2, -np.pi / 2, 180)    # rows: N → S
lon = np.linspace(-np.pi, np.pi, 360)            # cols: W → E
LON, LAT = np.meshgrid(lon, lat)
X = np.cos(LAT) * np.cos(LON)
Y = np.cos(LAT) * np.sin(LON)
Z = np.sin(LAT)

globe = ax.plot_surface(X, Y, Z, bounds=((-1, 1),) * 3)
globe.set_texture("earth.jpg", shade=True, cull_backfaces=True)
clear_texture()[source]#

Remove the image texture; the surface reverts to colormapped Z.

Return type:

None

property has_texture: bool#

True when an image texture is currently applied.

set_point_colors(colors)[source]#

Set (or clear) per-point colours on a scatter or voxels panel.

Parameters:

colors (list of "#rrggbb" strings, (N, 3) array, or None) – One colour per point / voxel. Floats are interpreted as 0–1 (or 0–255 when the max exceeds 1). None reverts to the single color for all elements.

Return type:

None

set_highlight(x, y, z, *, color='#ff1744', size=7.0)[source]#

Mark one 3-D point with an emphasised dot drawn on top.

The highlight is independent of the panel’s geometry — use it to flag the “current” item in a point cloud or on a surface (e.g. the orientation under a crosshair in an IPF explorer). Points on the far side of the data are drawn semi-transparent as a depth cue.

Parameters:
  • x (float) – Position in data coordinates.

  • y (float) – Position in data coordinates.

  • z (float) – Position in data coordinates.

  • color (str, optional) – CSS colour of the dot and ring. Default "#ff1744".

  • size (float, optional) – Dot radius in pixels. Default 7.

Return type:

None

See also

clear_highlight

Remove the highlight.

clear_highlight()[source]#

Remove the highlight point set by set_highlight().

Return type:

None

set_sphere(radius=1.0, *, color='#9e9e9e', alpha=0.15, wireframe=True)[source]#

Draw an origin-centred reference sphere behind the data.

Rendered as a shaded silhouette disk plus latitude/longitude wireframe arcs (far-side arcs dimmed). Scatter points on the far side of the sphere are also dimmed, so a point cloud on the sphere reads with correct depth — ideal for inverse-pole-figure / orientation plots of unit vectors.

Assumes origin-centred, isotropic bounds — pass bounds=((-r, r),) * 3 to the constructor so the sphere’s screen silhouette is a true circle.

Parameters:
  • radius (float, optional) – Sphere radius in data units. Default 1 (unit sphere).

  • color (str, optional) – Base CSS colour of the shading and wireframe. Default grey.

  • alpha (float, optional) – Opacity of the shaded silhouette (0–1). Default 0.15.

  • wireframe (bool, optional) – Draw latitude/longitude arcs. Default True.

Return type:

None

See also

clear_sphere

Remove the reference sphere.

clear_sphere()[source]#

Remove the reference sphere set by set_sphere().

Return type:

None

add_patch(points, *, frame='data', closed=True, geodesic=True, facecolor='#4fc3f7', edgecolor=None, alpha=0.3, back_alpha=0.3, linewidth=1.5, label='', name=None)[source]#

Draw a region (or, with closed=False, a path) on this panel.

Made for spheres: the region a detector sees on a master pattern, a grain’s spread of orientations on a pole sphere, the trace of a band. By default each edge follows the great circle between its two corners — the shortest way round the sphere, and exactly the shape a flat detector’s straight edge makes when projected onto it — so four corners are enough for a detector’s footprint.

The part of the patch behind the centre of the data is drawn dimmer (back_alpha), and where a geodesic patch wraps behind the sphere its outline follows the sphere’s edge rather than cutting across it.

Parameters:
  • points ((N, 3) array-like) – Corners (or path points) in data coordinates.

  • frame ("data" | "world") – "data" (default) turns the patch with the data when set_rotation() changes — a feature of the object. "world" keeps it fixed while the data turns under it — a detector, a beam, anything that belongs to the instrument. Both move with the camera.

  • closed (bool) – Join the last point back to the first and fill the inside. False draws an open path with no fill.

  • geodesic (bool) – Join points by great-circle arcs about the centre of the data bounds (default). False joins them with straight lines.

  • facecolor (str) – Fill and outline colours; edgecolor defaults to facecolor.

  • edgecolor (str) – Fill and outline colours; edgecolor defaults to facecolor.

  • alpha (float) – Opacity of the fill, 0–1. The outline is drawn opaque.

  • back_alpha (float) – Opacity multiplier for the part behind the centre, 0–1.

  • linewidth (float) – Outline width in pixels; 0 hides the outline.

  • label (str) – Text drawn at the patch’s centre while it faces the camera.

  • name (str, optional) – Key in patches. Re-using a name replaces that patch.

Returns:

Handle with set() and remove().

Return type:

Patch3D

remove_patch(patch)[source]#

Take off a patch, given its handle or its name.

Return type:

None

property patches: dict#

The panel’s patches by name, as Patch3D handles.