vectorose.plotting#

Plotting functions for VectoRose.

After constructing the various histograms using the classes and functions present in tregenza_sphere, triangle_sphere and polar_data, this module can be used to visualise the results.

Classes#

CardinalDirection

Cardinal directions.

RotationDirection

Rotation directions.

AngularUnits

Angular units.

SphereProjection

Projection type for 3D figures.

ViewingPlanes

Built-in viewing angles.

SpherePlotter

Produce beautiful, fast 3D sphere plots using PyVista.

Functions#

produce_1d_scalar_histogram(→ matplotlib.pyplot.Axes)

Produce a 1D scalar histogram.

produce_polar_histogram_plot(, axis_ticks_unit, ...)

Produce a 1D polar histogram plot.

produce_phi_theta_polar_histogram_plots(...)

Produce and show the 1D polar phi and theta histograms.

produce_labelled_3d_plot(, theta_label_positions, ...)

Modify a 3D Matplotlib plot to label it with spherical axes.

produce_3d_triangle_sphere_plot(...)

Produce a 3D sphere plot based on a triangle mesh.

produce_3d_tregenza_sphere_plot(...)

Produce a 3D sphere plot based on a Tregenza sphere.

construct_uv_sphere_vertices(→ numpy.ndarray)

Compute the vertices for a UV sphere with rectangular faces.

construct_uv_sphere_mesh(→ pyvista.PolyData)

Construct a UV sphere mesh.

__update_sphere_viewing_angle(...)

Update the sphere viewing angle.

animate_sphere_plot(→ matplotlib.animation.FuncAnimation)

Animate the sphere plot.

construct_confidence_cone(...)

Construct the patches for a confidence cone.

produce_3d_confidence_cone_plot(...)

Produce a 3D confidence cone plot.

Module Contents#

class vectorose.plotting.CardinalDirection[source]#

Bases: str, enum.Enum

Cardinal directions.

This string-based enumerated type is useful when preparing 2D polar figures. Members reflect cardinal directions, which may be used to indicate positions on circular (polar) axes. The values are consistent with the Matplotlib convention (see matplotlib.projections.polar.PolarAxes.set_theta_zero_location() for details).

Members:
  • NORTH – Location directly upwards.

  • NORTH_WEST – Location in the upper left corner.

  • WEST – Location on the left side.

  • SOUTH_WEST – Location in the lower left corner.

  • SOUTH – Location directly downwards.

  • SOUTH_EAST – Location in the lower right corner.

  • EAST – Location on the right side.

  • NORTH_EAST – Location in the upper right corner.

See also

matplotlib.projections.polar.PolarAxes.set_theta_zero_location

Set the zero position of a polar plot using one of the member values for this type.

NORTH = 'N'#
NORTH_WEST = 'NW'#
WEST = 'W'#
SOUTH_WEST = 'SW'#
SOUTH = 'S'#
SOUTH_EAST = 'SE'#
EAST = 'E'#
NORTH_EAST = 'NE'#
class vectorose.plotting.RotationDirection[source]#

Bases: enum.IntEnum

Rotation directions.

This integer-based enumerated type represents two-dimensional rotation direction. The convention used is consistent with the Matplotlib documentation (see :meth:matplotlib.projections.polar.PolarAxes.set_theta_direction for details).

Members:
  • CLOCKWISE – Clockwise, or rightward rotation.

  • COUNTER_CLOCKWISE – Counter-clockwise, anti-clockwise, or leftward rotation.

See also

matplotlib.projections.polar.PolarAxes.set_theta_direction

Set the rotation direction of a polar plot using one of the member values for this type.

CLOCKWISE = -1#
COUNTER_CLOCKWISE = 1#
class vectorose.plotting.AngularUnits[source]#

Bases: enum.Enum

Angular units.

This enumerated type represents angular units (degrees or radians). It does not provide any implementation for converting from one to the other, as this functionality is already very well included in NumPy.

Members:
  • DEGREES – Represent angles in degrees (typically in the range 0 to 360 or -180 to +180).

  • RADIANS – Indicates that angle is in radians (typically in the range 0 to \(2\pi\) or \(-\pi\) to \(\pi\)).

See also

numpy.degrees

Convert numeric values from radians into degrees.

numpy.radians

Convert numeric values from degrees into radians.

DEGREES = 0#
RADIANS = 1#
class vectorose.plotting.SphereProjection[source]#

Bases: enum.Enum

Projection type for 3D figures.

Enumerated type representing the projection type for 3D figures. The values of the members are compatible with the Matplotlib 3D axes method mpl_toolkits.mplot3d.axes3d.Axes3D.set_proj_type().

Members:
  • ORTHOGRAPHIC – Orthographic projection.

  • PERSPECTIVE – Perspective projection.

ORTHOGRAPHIC = 'ortho'#
PERSPECTIVE = 'persp'#
class vectorose.plotting.ViewingPlanes[source]#

Bases: str, enum.Enum

Built-in viewing angles.

Each member represents a viewing plane (or the isometric angle) defined in PyVista.

See also

pyvista.Plotter.camera_position

The function used to set the view to one of these planes.

XY = 'xy'#
XZ = 'xz'#
YZ = 'yz'#
YX = 'yx'#
ZX = 'zx'#
ZY = 'zy'#
ISO = 'iso'#
class vectorose.plotting.SpherePlotter(sphere_meshes: List[pyvista.PolyData] | pyvista.PolyData, visible_shells: List[int] | None = None, off_screen: bool = None, cmap: str = 'viridis')[source]#

Produce beautiful, fast 3D sphere plots using PyVista.

_sphere_meshes: List[pyvista.PolyData]#

The meshes representing individual shells.

_largest_radius: float#

The largest radius of a plotted sphere.

_active_shell: int#

The index of the currently-active shell.

_visible_shells: List[int]#

The indicies of the shells to plot as visible.

_active_shell_opacity: float#

The opacity of the currently active shell.

_inactive_shell_opacity: float#

The opacity of the inactive shells.

_plotter: pyvista.Plotter | None#

Plotter to use to visualise the spheres.

_sphere_actors: List[pyvista.Actor]#

The actors representing the plotted spheres.

_phi_axis_actor: pyvista.Actor | None#

The actor representing the semicircular phi axis.

_theta_axis_actor: pyvista.Actor | None#

The actor representing the circular theta axis.

_point_label_actor: vtk.vtkActor2D | None#

The actor controlling the point labels.

_picked_cells: List[pyvista.UnstructuredGrid]#

List of picked cells.

_picked_cell_actors: Dict[int, pyvista.Actor]#

Actors for picked faces.

_picking_active: bool#

Indicate whether cell picking is active.

cmap: str#

The colour map to use when visualising the data.

_has_movie_open: bool#

Indicate whether a movie is currently a being manually written.

property sphere_meshes: List[pyvista.PolyData]#

Access the wrapped sphere meshes.

property phi_axis_visible: bool#

Indicate whether the phi axis is visible.

property theta_axis_visible: bool#

Indicate whether the theta axis is visible.

property axis_labels_visible: bool#

Indicate whether the axis labels are visible.

property sliders_visible: bool#

Indicate whether the sliders are visible.

If the plot was created without sliders, this always evaluates to False.

property scalar_bars_visible: bool#

Indicate whether the scalar bars are visible.

If there are no scalar bars, this will always return False.

property active_shell: int#

Get or set the active shell index.

Warning

This property describes the index, not the shell number. The values provided here are offset by one compared with the slider values.

property active_shell_opacity: float#

Get the active shell opacity.

Active sphere opacity between 0 (transparent) and 1 (opaque).

property inactive_shell_opacity: float#

Get the opacity of the inactive shells.

Inactive sphere opacity between 0 (transparent) and 1 (opaque).

property radius: float#

Access the sphere radius.

property has_produced_plot: bool#

Indicate whether the plot has been produced.

property current_phi: float#

Get the phi value under the current view in degrees.

Notes

This value makes the most sense if the camera has the origin as the focal point.

property current_theta: float#

Get the theta value under the current view in degrees.

Notes

This value makes the most sense if the camera has the origin as the focal point.

property current_azimuth: float#

Get the current azimuth in degrees between 0 and 360.

Notes

This value is related to the current_theta, but not identical, as it is measured clockwise from the +x axis. This value is 90° offset of the \(\theta\) as defined in mathematical spherical coordinates.

property current_elevation: float#

Get the current elevation in degrees between 0 and 180.

Notes

This value is the same as that returned by current_phi.

property current_roll: float#

Get the current roll in degrees, measured between 0 and 360.

Notes

This value is computed by undoing the azimuth and elevation and then measuring the angle that transformed vector and the original camera up vector [0, 1, 0].

property cell_picking_active: bool#

Indicate whether interactive cell picking is active.

property picked_cells: pandas.DataFrame#

Get picked face scalar data.

Returns:

pandas.DataFrame – All cell scalar data for the picked mesh cells. These values can then be used by the SphereBase sphere to extract vectors from the picked cells. If no cells are picked, an empty pandas.DataFrame is produced. See Notes for full details on the format.

Notes

The return pandas.DataFrame always contains at least the following keys:

  • index - the cell index within the sphere mesh

  • orientation bin information - sphere-dependent keys providing the orientation bin

  • frequency - the frequency value associated with the face

  • shell - if multiple shells are present in the data, the shell corresponding to the selected cell (absent if only one shell)

Other keys may be present, but these are the ones most important for VectoRose.

property has_movie_open: bool#

Indicate whether a movie is currently being manually written.

_get_spherical_coordinates_from_camera() numpy.ndarray[source]#

Get the spherical coordinates for the camera location.

Returns:

numpy.ndarray – Array of shape (3,) containing the phi, theta and radius for the camera’s position in 3D space.

Notes

The values in this function are not recentred if the camera is translated in space.

_update_active_sphere_opacity(new_opacity: float)[source]#

Update the opacity level of the active sphere.

_update_inactive_sphere_opacity(new_opacity: float)[source]#

Update the opacity level of the inactive spheres.

_update_active_sphere(new_selected_shell_number: float)[source]#

Update the active sphere number.

_update_show_axes(show_axes: bool)[source]#

Update whether the axes are drawn.

pick_cells(cell_indices: pandas.Series | pandas.DataFrame)[source]#

Pick cells in the plotted sphere or spherical shells.

Parameters:

cell_indices – Either a pandas.Series containing the cell indices in the case of purely directed or oriented data, or a pandas.DataFrame containing a column shell for the magnitude shell and index for the cell index.

Warning

If the same cell is provided an even number of times, it will become deselected. Each selection is a toggle.

_pick_cells(cell: pyvista.UnstructuredGrid)[source]#

Callback when a mesh face is picked.

add_spherical_axes(plot_phi: bool = True, plot_theta: bool = True, phi_increment: int = 30, theta_increment: int = 30, axis_distance_fixed: float = 0.2, axis_distance_relative: float = 1, axis_thickness: float = 0.05)[source]#

Add spherical axes to the current plotter.

Parameters:
  • plot_phi – Indicate that the phi axis is to be plotted.

  • plot_theta – Indicate that the theta axis is to be plotted.

  • phi_increment – Label increment for the phi values.

  • theta_increment – Label increment for the theta values.

  • axis_distance_fixed – Fixed distance from the outer shell to the axis.

  • axis_distance_relative – Relative distance from the outer shell to the axis.

  • axis_thickness – Absolute thickness of the axes.

clear_axes()[source]#

Clear the plotted axes.

clear_plotter()[source]#

Clear and remove the current plotter.

clear_picked_cells()[source]#

Clear the picked cells.

produce_plot(add_sliders: bool = True, series_name: str = 'frequency', min_value: float | None = None, max_value: float | None = None, use_log_scale: bool = False)[source]#

Produce the 3D visual plot for the current spheres.

Parameters:
  • add_sliders – Indicate whether the opacity sliders should be added to the plotting window.

  • series_name – Name of the scalars to consider.

  • min_value – Optional minimum value for the colour map.

  • max_value – Optional maximum value for the colour map.

  • use_log_scale – Indicate whether to use a log scale.

Warning

This function produces the pyvista.Plotter. The method SpherePlotter.show() must be called to view the plot.

If use_log_scale is set to True, the input scalar data must be greater than zero.

show(*args, **kwargs)[source]#

Show the plotter window.

Parameters:
Raises:

AssertionError – If the plot has not yet been produced using the method produce_plot().

See also

pyvista.Plotter.show

Method used to show a PyVista plotter.

close(deep_clean: bool = True)[source]#

Close the plotting window and clear the associated memory.

Parameters:

deep_clean – Indicate whether a deep clean of the memory should be performed after closing.

rotate_to_view(phi: float | None = None, theta: float | None = None, use_degrees: bool = True, zoom: float | None = None, focal_depth: float | None = None)[source]#

Move the camera to focus on a specific orientation.

Parameters:
  • phi – The co-latitude to centre on. If None, then the value of phi is unchanged.

  • theta – The azimuthal angle to centre on. If None, then the value of theta is unchanged.

  • use_degrees – Indicate whether the angles should be interpreted in degrees.

  • zoom – Factor to zoom the view as a floating point value. See pyvista.Camera.zoom() for a full explanation.

  • focal_depth – Distance between the camera and the focal point.

See also

pyvista.Plotter.camera_position

Information about the camera from the plotter, used to compute the orientation angles.

pyvista.Camera.zoom

Control the camera zoom.

Notes

The point of focus of the camera remains at the origin. This method simply changes the position of the camera in space and changes the up direction.

rotate_camera_euler(azimuth: float, elevation: float, roll: float, use_degrees: bool = True)[source]#

Rotate the camera using specified intrinsic Euler angles.

Parameters:
  • azimuth – Angular rotation about the global Z-axis, measured counter-clockwise from the positive X-axis.

  • elevation – Angular tilt about the transformed X-axis, measured counter-clockwise from the positive Z-axis down.

  • roll – Camera rotation about the transformed Z-axis, measured counter-clockwise.

  • use_degrees – Indicate whether angles should be considered in degrees.

Warning

Note the definitions of the angles! These don’t correspond to the angles \(\phi\) and \(\theta\) defined elsewhere.

Also, the current_roll, current_azimuth and current_elevation may not match the values passed here due to redundancy.

Notes

Before rotating, the view is aligned with the XY plane to ensure reproducible behaviour.

The camera rotation is applied in the sequence ZXZ. First the camera is rotated about the local Z axis to set the azimuth. Then, the camera is rotated about the new local X-axis to set the correct elevation. Then, the camera is rolled along the new local Z axis.

Additional information about Euler angles can be found at https://en.wikipedia.org/wiki/Euler_angles.

open_movie_file(filename: str, quality: int = 5, fps: int = 24)[source]#

Open a movie file to record an animation.

Parameters:
  • filename – The destination for the created video. Must end with either .mp4 or .gif.

  • quality – Image quality for the video export, between 0 and 10. Ignored for exports as GIF.

  • fps – Frame rate, number of frames per second in the exported video.

Warning

This method only opens the video file. It does not save any of the frames. These must be written using the write_frame() method and then the file must be closed using close_movie().

See also

pyvista.Plotter.open_movie

The wrapped function that actually creates the movie file.

write_frame

Add frames to the open movie.

close_movie

Close and finalise the current movie.

write_frame()[source]#

Add a new frame to the current movie.

Warning

The current plotter must have a movie file that is open.

close_movie()[source]#

Close the movie currently being written.

Warning

The current plotter must have a movie file that is open.

produce_rotating_video(filename: str, quality: int = 5, fps: int = 24, zoom_factor: float = 1.0, number_of_frames: int = 36, vertical_shift: float | None = None, hide_sliders: bool = True)[source]#

Produce a video orbiting around the sphere.

Using the current plotter, produce a video orbiting around the visible shell. If there is no current plotter, a new one is produced.

Parameters:
  • filename – Movie export filename, with extension provided.

  • quality – Video export quality, between 0 and 10.

  • fps – Frame rate for the exported video.

  • zoom_factor – Factor to zoom when creating the frames.

  • number_of_frames – Total number of frames to produce in the video. A higher number results in a smoother animation, but a larger file and longer processing time.

  • vertical_shift – Upward shift of the orbital plane with respect to the ground.

  • hide_sliders – Indicate whether to hide the sliders when producing the video.

See also

pyvista.Plotter.generate_orbital_path

generate the path necessary for the animation.

References

This code is based on an example from the PyVista documentation, found at https://docs.pyvista.org/examples/02-plot/orbit.

produce_shells_video(filename: str, quality: int = 5, fps: int = 24, zoom_factor: float = 1.0, inward_direction: bool = True, boomerang: bool = False, azimuth: float | None = None, elevation: float | None = None, hide_sliders: bool = True, add_shell_text: bool = False)[source]#

Produce a video revealing all shells in a plot.

Parameters:
  • filename – Movie export filename, including file extension.

  • quality – Video export quality, between 0 and 10.

  • fps – Frame rate for the exported video.

  • zoom_factor – Factor to zoom when creating the frames.

  • inward_direction – Indicate whether the animation should progress from the outermost shell inwards (True) or from the innermost shell outwards (False).

  • boomerang – Indicate whether the animation should have a boomerang effect, where it is symmetric in time.

  • azimuth – Camera azimuthal angle in degrees (theta). If not specified, the current plotter’s angles are used.

  • elevation – Camera elevation angle in degrees (phi). If not specified, the current plotter’s angles are used.

  • hide_sliders – Indicate whether the sliders should be hidden before producing the video.

  • add_shell_text – Indicate whether to show text at the bottom of the screen indicating the shell number.

hide_sliders()[source]#

Hide the plotter’s slider widgets.

show_sliders()[source]#

Show the plotter’s slider widgets.

hide_scalar_bars()[source]#

Hide the scalar bars.

show_scalar_bars()[source]#

Show the scalar bars.

show_axes()[source]#

Show the spherical axes.

hide_axes()[source]#

Hide the spherical axes.

export_screenshot(filename: str, transparent_background: bool = True, window_size: tuple[int, int] | None = None, scale: int | None = None, hide_sliders: bool = True, hide_scalar_bar: bool = False)[source]#

Export a screenshot from the plotter.

Parameters:
  • filename – Output destination for the screenshot, including file extension. Must be of type PNG, bitmap, JPEG or TIFF.

  • transparent_background – Indicate whether the background should be transparent.

  • window_size – Desired window size before exporting.

  • scale – Factor by which to scale the window before exporting to increase resolution.

  • hide_sliders – Indicate whether to hide sliders before exporting. If no sliders have been added to the plot, this option has no effect.

  • hide_scalar_bar – Indicate whether to hide the scalar bar when exporting. The scalar bar will be made visible again after exporting.

See also

pyvista.Plotter.screenshot

Function wrapped by this function, which actually produces the screenshot. The current function borrows some parameters from this function.

export_graphic(filename: str, title: str, raster: bool = True, painter: bool = True, window_size: tuple[int, int] | None = None, scale: int | None = None, hide_sliders: bool = True, hide_scalar_bar: bool = False)[source]#

Export a graphic from the plotter.

Parameters:
  • filename – Output destination for the graphic, including file extension. Must be of type SVG, PDF, TEX, PS or EPS.

  • title – Name of the graphics (see PyVista documentation).

  • raster – Indicate whether to write the properties as a raster image (see PyVista documentation).

  • painter – Indicate whether to perform a certain painting step (see PyVista documentation).

  • window_size – Desired window size before exporting.

  • scale – Factor by which to scale the window before exporting to increase resolution.

  • hide_sliders – Indicate whether to hide sliders before exporting. If no sliders have been added to the plot, this option has no effect.

  • hide_scalar_bar – Indicate whether to hide the scalar bar when exporting. The scalar bar will be made visible again after exporting.

See also

pyvista.Plotter.save_graphic

Function wrapped by this function, which actually produces the graphic. The current function borrows some parameters from this function.

set_view_plane(viewing_plane: ViewingPlanes)[source]#

Set the plotter camera to a predefined viewing angle.

vectorose.plotting.produce_1d_scalar_histogram(counts: pandas.Series | numpy.ndarray, bin_edges: numpy.ndarray, fill: bool = True, ax: matplotlib.pyplot.Axes | None = None, log: bool = False, **kwargs) matplotlib.pyplot.Axes[source]#

Produce a 1D scalar histogram.

This function is mostly used to visualise the marginal magnitude histogram.

Parameters:
  • counts – The counts in each bin.

  • bin_edges – The edges of the bins used to compute the histogram.

  • fill – Indicate whether to fill the histogram. If False then only an outline of the bars is drawn.

  • ax – Optional axes on which to plot. If None, then new axes are created.

  • log – Indicate whether to use a logarithmic scale for the y-axis.

  • **kwargs – Keyword arguments for plotting the histogram. See matplotlib.axes.Axes.bar() and matplotlib.patches.Rectangle for more details.

Returns:

matplotlib.axes.Axes – The axes containing the histogram plot.

See also

matplotlib.pyplot.bar

create a bar plot using provided heights.

vectorose.plotting.produce_polar_histogram_plot(ax: matplotlib.projections.polar.PolarAxes, data: numpy.ndarray, bins: numpy.ndarray, zero_position: CardinalDirection = CardinalDirection.NORTH, rotation_direction: RotationDirection = RotationDirection.CLOCKWISE, plot_title: str | None = None, label_axis: bool = True, axis_ticks: numpy.ndarray = np.arange(0, 360, 30), axis_ticks_unit: AngularUnits = AngularUnits.DEGREES, colour: str = 'C0', max_angle: float | None = None, r_min: float = 0, r_max: float | None = None) matplotlib.projections.polar.PolarAxes[source]#

Produce a 1D polar histogram plot.

Produce a 1D polar histogram using the specified data on provided axes.

Parameters:
  • ax – Matplotlib matplotlib.projections.polar.PolarAxes on which to plot the data.

  • data – Histogram data to plot. This should have the same size as bins.

  • bins – Lower edge of each histogram bin.

  • zero_position – Zero-position on the polar axes, expressed as a member of the enumerated class CardinalDirection.

  • rotation_direction – Rotation direction indicating how the bin values should increase from the zero-point specified in zero_position, represented as a member of RotationDirection.

  • plot_title – Optional title of the plot.

  • label_axis – Indicate whether the circumferential axis should be labelled.

  • axis_ticks – Axis ticks for the histogram. Units specified in axis_ticks_unit.

  • axis_ticks_unitAngularUnits indicating what unit should be used for specifying the axis ticks. Default is AngularUnits.DEGREES.

  • colour – Histogram bar colour. Must be a valid matplotlib colour [1].

  • max_angle – Maximum angle to represent on the angular axis in degrees. Must be between 0 and 360°. If None, a complete circle is drawn.

  • r_min – Minimum bound along the r axis. If None, then set automatically from the data.

  • r_max – Maximum bound along the r axis. If None, then set automatically from the data.

Returns:

matplotlib.projections.polar.PolarAxes – The PolarAxes used for plotting.

Warning

The axes provided must be created using projection="Polar".

The max_angle parameter allows for a portion of the circular plot to be drawn. Any values beyond this maximum will be truncated.

See also

matplotlib.projections.polar.PolarAxes

Polar axes used for plotting the polar histogram.

References

vectorose.plotting.produce_phi_theta_polar_histogram_plots(phi_data: pandas.DataFrame, theta_data: pandas.DataFrame, zero_position_2d: CardinalDirection = CardinalDirection.NORTH, rotation_direction: RotationDirection = RotationDirection.CLOCKWISE, use_degrees: bool = True, use_counts: bool = False, plot_title: str | None = None, fig: matplotlib.pyplot.Figure | None = None, r_phi_min: float | None = 0, r_phi_max: float | None = None, r_theta_min: float | None = 0, r_theta_max: float | None = None) matplotlib.pyplot.Figure[source]#

Produce and show the 1D polar phi and theta histograms.

This function takes in 2D binned histogram input and shows a 2-panel figure containing the theta and phi polar histograms.

Parameters:
  • phi_data – Histogram data for the phi angle.

  • theta_data – Histogram data for the theta angle.

  • zero_position_2d – The CardinalDirection where zero should be placed in the 1D polar histograms (default: North).

  • rotation_direction – The RotationDirection of increasing angles in the 1D polar histograms (default: clockwise).

  • use_degrees – Indicate whether the values are in degrees. If True, values are assumed to be in degrees. Otherwise, radians are assumed.

  • use_counts – Indicate whether the bar heights should reflect the counts, as opposed to the frequencies.

  • plot_title – Title of the overall plot (optional).

  • fig – Figure on which to produce the plots. If None, a new figure is created.

  • r_phi_min – Minimum r-axis value for the phi plot. If None, computed from the data.

  • r_phi_max – Maximum r-axis value for the phi plot. If None, computed from the data.

  • r_theta_min – Minimum r-axis value for the theta plot. If None, computed from the data.

  • r_theta_max – Maximum r-axis value for the theta plot. If None, computed from the data.

Returns:

matplotlib.figure.Figure – The figure containing the polar histogram plots.

See also

produce_polar_histogram_plot

Create 1D polar histograms in isolation from 1D histogram data.

vectorose.plotting.produce_labelled_3d_plot(ax: mpl_toolkits.mplot3d.axes3d.Axes3D, radius: float, limits_factor: float = 1.1, plot_title: str | None = None, sphere_projection: SphereProjection = SphereProjection.ORTHOGRAPHIC, plot_phi_axis: bool = True, plot_theta_axis: bool = True, label_phi_axis: bool = True, label_theta_axis: bool = True, phi_label_positions: numpy.ndarray = np.arange(0, np.pi + 0.01, np.pi / 6), theta_label_positions: numpy.ndarray = np.arange(0, 2 * np.pi, np.pi / 6), phi_axis_colour: str = 'black', theta_axis_colour: str = 'black', hide_cartesian_axes: bool = True, hide_cartesian_axis_labels: bool = False, hide_cartesian_axis_ticks: bool = True, plot_colour_bar: bool = False, minimum_value: float | None = None, maximum_value: float | None = None, colour_map: str = 'viridis', colour_bar_kwargs: dict[str, Any] | None = None, axis_label_factor: float = 1.4, axis_tick_factor: float = 1.6, norm: matplotlib.colors.Normalize | None = None) mpl_toolkits.mplot3d.axes3d.Axes3D[source]#

Modify a 3D Matplotlib plot to label it with spherical axes.

Modify existing axes to add spherical phi and theta axes, as well as labels and a colour bar.

Parameters:
  • ax – Axes to modify. These must be 3D axes.

  • radius – Sphere radius in the 3D plot. This value is multiplied by the limits_factor to obtain the radius of the spherical axes.

  • limits_factor – Factor used to add padding to the sphere, by default 1.1. The same factor is used along all axes, and is multiplied by the radius of the sphere to define the axis bounds.

  • plot_title – Title of the plot produced (optional).

  • sphere_projection – Projection used to plot the sphere, by default SphereProjection.ORTHOGRAPHIC

  • plot_phi_axis – Indicate whether the phi axis should be plotted in 3D.

  • plot_theta_axis – Indicate whether the theta axis should be plotted in 3D.

  • label_phi_axis – Indicate whether to label the phi axis.

  • label_theta_axis – Indicate whether to label the theta axis.

  • phi_label_positions – Indicate angular positions for the labels for phi along its circular axis.

  • theta_label_positions – Indicate angular positions for the labels for theta along its circular axis.

  • phi_axis_colour – Colour for the phi axis.

  • theta_axis_colour – Colour for the theta axis..

  • hide_cartesian_axes – Indicate whether to hide the Cartesian axes, by default True.

  • hide_cartesian_axis_labels – Indicate whether to hide the Cartesian axis labels, by default False. This has no effect if hide_cartesian_axes is True.

  • hide_cartesian_axis_ticks – Indicate whether to hide the Cartesian axis ticks, by default True.

  • plot_colour_bar – Indicate whether to plot the colour bar, by default False.

  • minimum_value – Minimum data value. Required if plotting the colour bar.

  • maximum_value – Maximum data value. Required if plotting the colour bar.

  • colour_map – Colour map for the colour bar.

  • colour_bar_kwargs – Keyword arguments for the colour bar.

  • norm – Normaliser to use for the colour bar (if applicable)

  • axis_tick_factor – Multiplicative factor providing the distance from the origin to the plotted axes and axis tick labels, based on the sphere radius.

  • axis_label_factor – Multiplicative factor providing the distance from the origin to the plotted axis labels, based on the sphere radius.

Returns:

mpl_toolkits.mplot3d.axes3d.Axes3D – The same axes as ax, with the new elements added.

vectorose.plotting.produce_3d_triangle_sphere_plot(ax: mpl_toolkits.mplot3d.axes3d.Axes3D, sphere: vectorose.triangle_sphere.TriangleSphere, face_counts: pandas.Series, colour_map: str = 'viridis', sphere_alpha: float = 1.0, norm: matplotlib.pyplot.Normalize | None = None, **kwargs: dict[str, Any] | None) mpl_toolkits.mplot3d.axes3d.Axes3D[source]#

Produce a 3D sphere plot based on a triangle mesh.

Using the provided axes, plot a sphere with face colours corresponding to the provided values. This plot is generated using Matplotlib.

Parameters:
  • ax – Axes on which to plot the sphere.

  • sphere – Triangle sphere to plot.

  • face_counts – Values assigned to each face in the sphere.

  • colour_map – Colour map used to colour the sphere, by default “viridis”.

  • norm – Optional matplotlib.colors.Normalize object to use to normalise the colours.

  • sphere_alpha – Opacity of the sphere.

  • **kwargs – Keyword arguments for the plot labelling. See produce_labelled_3d_plot() for options.

Returns:

mpl_toolkits.mplot3d.axes3d.Axes3D – The axes on which the provided sphere is plotted.

Warning

The provided axes must have the projection set to 3D using projection="3d".

The histogram data provided must occupy the entire sphere. No manipulations will be performed in this function to get the face colours to match the number of faces.

See also

vectorose.triangle_sphere.TriangleSphere

Produce a sphere and histogram labellings to pass to this function.

produce_labelled_3d_plot

Label the axes of the 3D plot.

produce_3d_tregenza_sphere_plot

Similar function for a Tregenza sphere.

vectorose.plotting.produce_3d_tregenza_sphere_plot(ax: mpl_toolkits.mplot3d.axes3d.Axes3D, tregenza_sphere: vectorose.tregenza_sphere.TregenzaSphere, histogram_data: pandas.Series | None = None, sphere_alpha: float = 1.0, colour_map: str = 'viridis', norm: matplotlib.pyplot.Normalize | None = None, **kwargs) mpl_toolkits.mplot3d.axes3d.Axes3D[source]#

Produce a 3D sphere plot based on a Tregenza sphere.

Using the provided axes, plot a Tregenza sphere with face colours corresponding to the provided histogram values. This plot is generated using Matplotlib.

Parameters:
  • ax – Axes on which to plot the sphere.

  • tregenza_sphere – Tregenza sphere on which to plot the values.

  • histogram_data – Histogram data to plot. The length of this list must correspond to the number of rings in the tregenza_sphere and the length of each entry must correspond to the respective patch count.

  • sphere_alpha – Opacity of the sphere.

  • colour_map – Colour map to use when plotting the sphere, by default “viridis”.

  • norm – Optional matplotlib.colors.Normalize object to use to normalise the colours.

  • **kwargs – Keyword arguments for the plot labelling. See produce_labelled_3d_plot() for options.

Returns:

mpl_toolkits.mplot3d.axes3d.Axes3D – The axes on which the provided sphere is plotted.

Warning

The histogram data must have a size matching the provided Tregenza sphere.

vectorose.plotting.construct_uv_sphere_vertices(phi_steps: int = 80, theta_steps: int = 160, radius: float = 1) numpy.ndarray[source]#

Compute the vertices for a UV sphere with rectangular faces.

Construct a UV sphere where each ring has the same number of faces.

Parameters:
  • phi_steps – Number of faces along the phi axis.

  • theta_steps – Number of faces along the theta axis, within a ring.

  • radius – Sphere radius.

Returns:

numpy.ndarray – Array containing the Cartesian coordinates of the sphere vertices in a format to plot using Axes3D.plot_surface(). This array will have shape (theta_steps + 1, phi_steps + 1, 3) where the last axis corresponds to the X, Y, Z components.

Warning

This sphere should not be used to plot histograms. It is provided for visualisations that do not involve plotting data on the surface of the sphere.

Notes

The coordinates computed using this function can easily be used to plot a sphere using Axes3D.plot_surface(). To do so, the X, Y and Z coordinate sheets must be separated by indexing along the last axis.

vectorose.plotting.construct_uv_sphere_mesh(phi_steps: int = 80, theta_steps: int = 160, radius: float = 1) pyvista.PolyData[source]#

Construct a UV sphere mesh.

Parameters:
  • phi_steps – Number of phi rings to construct.

  • theta_steps – Number of theta bins in each ring.

  • radius – Sphere radius.

Returns:

pyvista.PolyData – Mesh containing the UV sphere.

vectorose.plotting.__update_sphere_viewing_angle(frame: int, sphere_axes: mpl_toolkits.mplot3d.axes3d.Axes3D, angle_increment: int) Iterable[mpl_toolkits.mplot3d.axes3d.Axes3D][source]#

Update the sphere viewing angle.

Updates the sphere viewing angle to be the current angle, with the azimuth increased by an increment.

Parameters:

frame – The number of the current frame in the animation (required to fit the animation signature, but unused here).

Returns:

Iterable of mpl_toolkits.mplot3d.axes3d.Axes3D – An iterable containing a reference to the 3D sphere axes.

vectorose.plotting.animate_sphere_plot(sphere_figure: matplotlib.figure.Figure, sphere_axes: mpl_toolkits.mplot3d.axes3d.Axes3D, rotation_direction: RotationDirection = RotationDirection.CLOCKWISE, angle_increment: int = 10, animation_delay: int = 250, reset_initial_orientation: bool = True) matplotlib.animation.FuncAnimation[source]#

Animate the sphere plot.

Create an animation of the sphere plot rotating about its central axis (i.e., the axis running from the sphere’s north pole to its south pole).

Parameters:
  • sphere_figure – The matplotlib.figure.Figure containing the sphere plot.

  • sphere_axes – The mpl_toolkits.mplot3d.axes3d.Axes3D containing the sphere plot. These axes must be 3D axes.

  • rotation_direction – Direction for the sphere to rotate. See RotationDirection for more information.

  • angle_increment – Increment of the angle in degrees for the rotation at each frame. This value should be positive.

  • animation_delay – Time delay between frames in milliseconds.

  • reset_initial_orientation – Indicate whether the sphere should be reset to its original orientation before recording the animation. This argument should be set to False to allow a custom starting position.

Returns:

matplotlib.animation.FuncAnimation – The matplotlib animation produced by the sphere rotation.

Warning

We recommend to hide the polar axis ticks while performing the animation. Otherwise, the result may look odd.

See also

matplotlib.animation.FuncAnimation

The class that serves as the basis for the animations created here.

mpl_toolkits.mplot3d.axes3d.Axes3D.view_init

The method used to update the 3D viewing angle to produce the animations.

vectorose.plotting.construct_confidence_cone(angular_radius: float, number_of_patches: int = 80, mean_orientation: numpy.ndarray | None = None, two_sided_cone: bool = True, use_degrees: bool = False, **kwargs) List[mpl_toolkits.mplot3d.art3d.Poly3DCollection][source]#

Construct the patches for a confidence cone.

Construct the triangular patches for a confidence cone with a specified angular radius, and optionally rotated to a specified mean direction.

Parameters:
  • angular_radius – Angular radius for the confidence cone bounds (in radians, unless the parameter use_degrees is True).

  • number_of_patches – Number of patches to construct. Increase for a better approximation to a cone.

  • mean_orientation – Mean orientation to rotate the confidence cone, in cartesian coordinates. If None, then the cone is not rotated and remains vertically oriented.

  • two_sided_cone – Indicate whether the cone should be two-sided. If True, two cones will be constructed, radiating from the centre. If False, then a single cone is created.

  • use_degrees – Indicate whether the provided angular radius is in degrees.

  • **kwargs – Keyword arguments for the patch construction. See Poly3DCollection for details.

Returns:

list of mpl_toolkits.mplot3d.art3d.Poly3DCollection – List of Poly3DCollection representing each patch of the confidence cone. These patches are triangular.

vectorose.plotting.produce_3d_confidence_cone_plot(ax: mpl_toolkits.mplot3d.axes3d.Axes3D, confidence_cone_patches: List[mpl_toolkits.mplot3d.art3d.Poly3DCollection], sphere_vertices: numpy.ndarray, sphere_radius: float = 1, sphere_alpha: float = 0.5, sphere_colour: str = '#a8a8a8', **kwargs) mpl_toolkits.mplot3d.axes3d.Axes3D[source]#

Produce a 3D confidence cone plot.

Using the provided confidence cone patches and sphere vertices, create a plot containing the confidence cone inside a sphere.

Parameters:
  • ax – Axes on which to plot. These must be 3D axes.

  • confidence_cone_patches – Patches for the confidence cone.

  • sphere_vertices – Vertices for the UV sphere.

  • sphere_radius – Radius of the sphere.

  • sphere_alpha – Sphere opacity level.

  • sphere_colour – Colour of the sphere.

  • **kwargs – Arguments passed to produce_labelled_3d_plot() to alter the labelling of the 3D axes.

Returns:

mpl_toolkits.mplot3d.axes3d.Axes3D – Axes on which the confidence cone has been plotted.

Warning

The provided axes must have been constructed using a 3D projection, by setting projection="3d".

See also

construct_confidence_cone

Generate the confidence cone patches.

construct_uv_sphere_vertices

Generate vertices for a quad-based sphere.